PHP code example of alexius-byte / rider-php

1. Go to this page and download the library: Download alexius-byte/rider-php 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/ */

    

alexius-byte / rider-php example snippets


Dotenv::load(__DIR__ . '/.env');

$_ENV['APP_ENV'];   // string
$_ENV['APP_DEBUG']; // bool
$_ENV['DB_PORT'];   // int

$router = new Router();

$router->get('/users', [UserController::class, 'index']);
$router->post('/users', [UserController::class, 'store']);
$router->put('/users/{id}', [UserController::class, 'update']);
$router->delete('/users/{id}', [UserController::class, 'destroy']);

// Closure
$router->get('/', function (array $params) {
    echo 'Hello';
});

$router->dispatch();

if ($error = $router->hasError()) {
    http_response_code($error); // 404 or 405
}

$router->group('/admin');
$router->get('/dashboard', [AdminController::class, 'dashboard']); // → /admin/dashboard
$router->get('/users', [AdminController::class, 'users']);         // → /admin/users

$router->resetGroup();
$router->get('/', [HomeController::class, 'index']); // → /

class AuthMiddleware extends AbstractMiddleware
{
    public function run(): bool
    {
        if (!isset($_SESSION['user'])) {
            return $this->json(['error' => 'Unauthorized'], 401);
        }
        return true;
    }
}

$router->middleware(AuthMiddleware::class, AnotherMiddleware::class);
$router->get('/profile', [UserController::class, 'profile']);

$router->resetMiddleware();

class SiteRoutes extends AbstractRoute
{
    public function run(): void
    {
        $this->get('/', [HomeController::class, 'index']);
        $this->post('/contact', [HomeController::class, 'contact']);
    }
}

$router->addRouters(new SiteRoutes());

$router->tracker(HttpMethod::GET, 'posts', PostController::class);
// GET /posts/index   → PostController::index()
// GET /posts/show    → PostController::show()
// GET /posts/create  → PostController::create()

class Product extends Model
{
    protected string $table      = 'products';
    protected string $primaryKey = 'id';
    protected bool   $timestamps = true;
    protected array  $fillable   = ['code', 'name', 'price'];
}

$db = new Product();

$db->findById(1);
$db->findAll();
$db->findBy('name', 'Notebook');
$db->first('email', '[email protected]');
$db->random();
$db->count();

$users = $db->sortBy($users, fn($u) => $u->name);

$users = $db->sortBy($users, fn($u) => match($u->status) {
    'active'  => 0,
    'pending' => 1,
    default   => 2,
});

$db->create(['code' => 'ABC', 'name' => 'Notebook', 'price' => 3500]);

$product = $db->findById(1);
$product->name = 'Updated';
$db->update($product);

$db->delete(1);
$db->truncate();
$db->deleteOlderThan(60, 'created_at'); // returns int (rows deleted)

$db->upsert(['id' => 1, 'name' => 'Notebook', 'price' => 3500]); // insert or update

$db->query('SELECT * FROM products WHERE price > ?', 100);
$db->query('SELECT * FROM products WHERE active = ? AND role = ?', [1, 'admin']);

$db->execute('UPDATE products SET active = 0 WHERE id = ?', [5]);

$db->transaction(function (Product $db) {
    $db->create(['code' => 'A', 'name' => 'A', 'price' => 10]);
    $db->delete(5);
});

$export = new ExportDatabase(__DIR__ . '/backup.sql');
$export->setExclude(['logs', 'sessions']);
$export->export();

$truncate = new TruncateTables();
$truncate->truncateAll(['users', 'migrations']);
$truncate->addTable('logs');
$truncate->truncate();

$users = new User();

$page = (new Paginator())->create(
    query: fn() => $users->findAll(),
    page: 1,
    perPage: 25,
);

$page = (new Paginator())->create(
    query: fn($limit, $offset) => $users->findAll($limit, $offset),
    page: 1,
    perPage: 25,
    count: fn() => $users->count(),
);

// Filtered
$page = (new Paginator())->create(
    query: fn($limit, $offset) => $users->findBy('status', 'active', limit: $limit, offset: $offset),
    page: 1,
    perPage: 25,
    count: fn() => $users->count('status', 'active'),
);

$page->data;        // array — records for the current page
$page->total;       // int   — total records across all pages
$page->perPage;     // int   — records per page (capped at 1 000)
$page->currentPage; // int   — current page number
$page->lastPage;    // int   — total number of pages
$page->from;        // int   — index of the first record shown (1-based), 0 when empty
$page->to;          // int   — index of the last record shown, 0 when empty
$page->hasNext;     // bool
$page->hasPrev;     // bool

class CreateUsersTable extends AbstractMigration
{
    public function up(): void
    {
        $this->execute("
            CREATE TABLE users (
                id         INT AUTO_INCREMENT PRIMARY KEY,
                name       VARCHAR(100) NOT NULL,
                email      VARCHAR(150) NOT NULL UNIQUE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ");
    }

    public function down(): void
    {
        $this->execute("DROP TABLE IF EXISTS users");
    }
}

class UserSeeder extends AbstractSeeder
{
    public function run(): void
    {
        $this->insert('users', [
            ['name' => 'Admin',  'email' => '[email protected]'],
            ['name' => 'Editor', 'email' => '[email protected]'],
        ]);
    }
}

$uploader = new UploadFiles('/var/app/storage/uploads');
$path = $uploader->upload($_FILES['photo'], AllowedType::Image);

$uploader = new UploadFiles('/var/app/storage/uploads', 10); // 10 MB

// Allow all origins
Cors::allow('*');

// Allow specific origins only
Cors::allow(['https://app.example.com', 'https://example.com']);

// With credentials (cookies / Authorization header)
Cors::allow(
    origins: ['https://app.example.com'],
    credentials: true
);

// Custom methods, headers, and cache duration
Cors::allow(
    origins: '*',
    methods: ['GET', 'POST'],
    headers: ['Content-Type', 'Authorization'],
    maxAge: 3600
);

$container = new Container();

// new instance on every get()
$container->bind(LoggerInterface::class, FileLogger::class);

// factory closure
$container->bind(Mailer::class, fn($c) => new Mailer($c->get(Config::class)));

// single instance for every get()
$container->singleton(Database::class, DatabaseMysql::class);

// pre-built instance
$container->instance('config', $config);

$logger = $container->get(LoggerInterface::class);

$container->has(LoggerInterface::class); // bool

class UserService
{
    public function __construct(
        private readonly UserRepository $repository,
        private readonly Mailer $mailer,
    ) {}
}

$service = $container->get(UserService::class);

$encrypted = SSL::encode('sensitive data', $key);
$plain     = SSL::decode($encrypted, $key);

SSL::generateKeyPair('/var/app/storage/keys', 'public', 'secret');
// → /var/app/storage/keys/public.pem
// → /var/app/storage/keys/secret.pem  (chmod 0600)

SSL::generateKeyPair('/var/app/storage/keys', 'public', 'secret', 4096); // custom bits

$cache = new ArrayCache();                          // in-memory, request lifetime
$cache = new FileCache('/var/app/storage/cache');   // persistent on disk

$cache->set('key', $value);           // no expiry
$cache->set('key', $value, 300);      // expires in 300 seconds
$cache->set('key', $value, new DateInterval('PT5M')); // DateInterval

$cache->get('key');                   // returns null if missing or expired
$cache->get('key', 'default');        // custom default

$cache->has('key');                   // bool — also evicts expired entries
$cache->delete('key');
$cache->clear();

$cache->setMultiple(['a' => 1, 'b' => 2], 60);

foreach ($cache->getMultiple(['a', 'b'], 0) as $key => $value) {
    // $key => $value
}

$cache->deleteMultiple(['a', 'b']);

$v = Validator::make($_POST)
    ->field('name')->ield('age')->>!$v->passes()) {
    $errors = $v->errors(); // ['field' => 'message', ...]
}

// Or throw on failure
$v->validate(); // throws ValidationException — message never carries user data

$v = Validator::make($_POST)
    ->field('email')
        ->ld('age')
        ->u must be at least 18 years old');

$data = Schema::object($_POST, [
    'name'     => 'string|min:2|max:100',
    'email'    => 'email|max:30',
    'age'      => 'int|min:18|max:120',
    'website'  => 'optional|url',
    'role'     => 'in:admin,editor,user',
    'slug'     => 'regex:/^[a-z0-9-]+$/',
    'document' => 'cpf',
]);

$data['name'];
$data['email'];

try {
    $data = Schema::object($_POST, ['email' => 'email']);
} catch (SchemaException $e) {
    $e->errors(); // ['email' => 'The email field must be a valid email address']
}
nginx
server {
    root /var/www/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;