PHP code example of naqla-sehia / naqla-framework

1. Go to this page and download the library: Download naqla-sehia/naqla-framework library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

naqla-sehia / naqla-framework example snippets




ad environment variables
(new \Dotenv\Dotenv(__DIR__ . '/../'))->load();

// Load routes



use NaqlaSehia\Http\Route;
use App\Controllers\HomeController;

// Closure route
Route::get('/', function() {
    view('dashboard', ['name' => 'World']);
});

// Controller route
Route::post('/users', [UserController::class, 'store']);

// GET route
Route::get('/users', [UserController::class, 'index']);



namespace App\Controllers;

use NaqlaSehia\Http\Request;

class UserController
{
    public function index()
    {
        $users = app()->db->read();
        view('users.index', ['users' => $users]);
    }

    public function store()
    {
        $request = request();
        
        $validator = validator()
            ->setRules([
                'name' => ',
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password'))
        ]);

        session()->setFlash('success', 'User created successfully');
        return back();
    }
}

$request = request();

// Get all input
$data = $request->all();

// Get specific input
$email = $request->input('email');
$email = $request->get('email', '[email protected]');

// Check if input exists
if ($request->has('email')) {
    // ...
}

// Get specific fields only
$fields = $request->only(['name', 'email']);

// Get all except specific fields
$fields = $request->except(['password']);

// Get request method
$method = $request->method(); // 'get', 'post', etc.

// Check request method
if ($request->isMethod('post')) {
    // ...
}

// Get path
$path = $request->path();

$response = app()->response;

// Set HTTP status code
$response->setStatusCode(200);
$response->setStatusCode(Response::HTTP_NOT_FOUND); // 404

// Redirect
$response->redirect('/dashboard');
$response->back();

// JSON response
$response->json(['success' => true]);

// Set headers
$response->setHeader('X-Custom-Header', 'value');

// Method chaining
$response->setStatusCode(201)->json(['id' => 1]);

$db = app()->db;

// Create
$db->create([
    'name' => 'John Doe',
    'email' => '[email protected]'
]);

// Read with filter
$users = $db->read('*', ['email', '=', '[email protected]']);
$users = $db->read(['name', 'email']);

// Update
$db->update(1, [
    'name' => 'Jane Doe'
]);

// Delete
$db->delete(1);

// Raw query
$results = $db->raw('SELECT * FROM users WHERE age > ?', [18]);

$validator = validator()
    ->setRules([
        'name' => '    'password' => '([
        'email' => 'Email Address',
        'password' => 'Password'
    ])
    ->make(request()->all());

if ($validator->fails()) {
    $errors = $validator->errors();
    $nameErrors = $validator->errors('name');
}

if ($validator->passes()) {
    // Process valid data
}

// Simple view
view('dashboard');

// With parameters
view('dashboard', [
    'user' => $user,
    'posts' => $posts
]);

// View in subdirectory (uses dot notation)
view('posts.index', ['posts' => $posts]);
// Renders: views/posts/index.php

<!DOCTYPE html>
<html>
<head>
    <title> echo $title ?? 'My App'; 

<h1>Welcome  echo $name; 

$session = app()->session;

// Set value
$session->set('user_id', 1);

// Get value
$userId = $session->get('user_id');

// Check existence
if ($session->exists('user_id')) {
    // ...
}

// Remove value
$session->remove('user_id');

// Flash messages (auto-removed after next request)
$session->setFlash('success', 'Operation completed');
$session->setFlash('error', 'Something went wrong');

// Get flash message
if ($session->hasFlash('success')) {
    $message = $session->getFlash('success');
}

// Get all config
$allConfig = config();

// Get specific config
$dbDriver = config('database.driver');
$appName = config('app.name', 'Default Name');

// Check config exists
if (config()->has('app.debug')) {
    // ...
}

// Set config
config('app.debug', false);
config(['app.name' => 'MyApp']);

// Environment variables
$debug = env('APP_DEBUG', false);

// Application instance
$app = app();

// Request instance
$request = request('name'); // Get 'name' input
$request = request(['name', 'email']); // Get only these fields

// Config helper
$name = config('app.name');

// View helper
view('dashboard', ['data' => $data]);

// Validation
$validator = validator();

// Hashing
$hash = bcrypt('password');

// Response
back(); // Redirect back

// Paths
base_path();       // Project root
config_path();     // config/ directory
database_path();   // database/ directory
public_path();     // public/ directory
view_path();       // views/ directory

// Other utilities
class_basename($class); // Get class name without namespace
value($value);          // Call if closure, otherwise return value

use NaqlaSehia\Support\Arr;

// Get value using dot notation
$value = Arr::get($array, 'user.name', 'default');

// Set value using dot notation
Arr::set($array, 'user.name', 'John');

// Check if key exists
Arr::has($array, 'user.email');

// Get only specific keys
$subset = Arr::only($array, ['name', 'email']);

// Get all except specific keys
$subset = Arr::except($array, ['password']);

// Add value if key doesn't exist
Arr::add($array, 'role', 'user');

// Remove keys
Arr::forget($array, ['password', 'token']);

// Flatten array
$flat = Arr::flatten($multidimensional);

// Get first/last element
$first = Arr::first($array);
$last = Arr::last($array);

use NaqlaSehia\Support\Str;

// Convert to lowercase
$lower = Str::lower('HELLO');

// Pluralization
$plural = Str::plural('user');    // 'users'
$singular = Str::singular('users'); // 'user'

// Plural if condition
$text = Str::plural_if(5, 'user'); // '5 users'

use NaqlaSehia\Support\Hash;

// Hash password with bcrypt
$hashed = Hash::make('password');

// Verify password
if (Hash::verify('password', $hashed)) {
    // Valid password
}

// Quick hash (not for passwords)
$hash = Hash::hash('data');

// 404 errors
// If route not found, displays views/errors/404.php

// HTTP Status Codes
$response->setStatusCode(Response::HTTP_NOT_FOUND);
$response->setStatusCode(Response::HTTP_INTERNAL_ERROR);
$response->setStatusCode(Response::HTTP_UNAUTHORIZED);

return [
    'driver' => env('DB_DRIVER', 'mysql'),
    'host' => env('DB_HOST', 'localhost'),
    'database' => env('DB_DATABASE'),
    'username' => env('DB_USERNAME'),
    'password' => env('DB_PASSWORD'),
];

return [
    'driver' => env('DB_DRIVER', 'sqlite'),
    'database' => database_path() . 'database.sqlite',
];



namespace App\Validation\Rules;

use NaqlaSehia\Validation\Rules\Contract\Rule;

class PhoneRule implements Rule
{
    public function apply($field, $value, $data = [])
    {
        return preg_match('/^[0-9]{10,15}$/', $value);
    }

    public function __toString()
    {
        return '%s must be a valid phone number';
    }
}

protected static array $map = [
    'phone' => App\Validation\Rules\PhoneRule::class,
    // ... other rules
];

app/
├── Models/
│   └── User.php
├── Controllers/
│   └── UserController.php
routes/
├── web.php
public/
├── index.php
├── css/
└── js/
database/
├── migrations/
└── database.sqlite
config/
├── app.php
├── database.php
└── mail.php
views/
├── layouts/
│   └── main.php
├── dashboard.php
└── errors/
    └── 404.php
vendor/
.env