PHP code example of rudra / framework

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

    

rudra / framework example snippets


$env = match (true) {
    getenv('IS_DDEV_PROJECT') === 'true' => 'ddev',
    php_sapi_name() === 'cli-server' => 'local',
    default  => 'production',
};


// Do NOT commit this file to Git (.gitignore)
return 'local'; // ← Set to: 'local', 'ddev', or 'production'



namespace App\Containers\Web\Controller;

use App\Containers\Web\WebController;
use Rudra\Router\Attribute\Routing;
use Rudra\Container\Facades\Request;

class HelloController extends WebController
{
    #[Routing(url: 'hello/:name', method: 'GET')]
    public function greet(string $name): void
    {
        echo "<h1>Hello, {$name}!</h1>";
        echo '<p>Your lucky number is: ' . random_int(1, 100) . '</p>';
    }
}



use Rudra\Router\RouterFacade as Router;
use App\Containers\Web\Controller\HelloController;

Router::get('hello/:name', [HelloController::class, 'greet']);

return [];

Router::get('hello/:name', function (string $name) {
    echo "Hello, {$name}!";
});

use Rudra\Auth\AuthFacade as Auth;

// Registration
$user = [
    'email'    => '[email protected]',
    'password' => Auth::bcrypt('password')
];

// Authentication (plain password vs hash from DB)
Auth::authentication($user, 'password', ['admin/dashboard', 'login']);

// Authorization check (redirects to 'login' if not authenticated)
if (!Auth::authorization(null, 'login')) {
    exit;
}

// Role-Based Access Control
if (!Auth::roleBasedAccess($currentRole, 'editor', 'error/403')) {
    exit;
}

use Rudra\EventDispatcher\EventDispatcherFacade as Dispatcher;

// Listeners — pub/sub with payload
Dispatcher::addListener('user.registered', [UserListener::class, 'onRegister']);
Dispatcher::dispatch('user.registered', ['id' => 1, 'email' => '...']);

// Observers — stateless notifications (no payload)
Dispatcher::attachObserver('before', [AuditObserver::class, 'onEvent']);
Dispatcher::notify('before');

use Rudra\Container\Facades\Request;
use Rudra\Container\Facades\Session;
use Rudra\Validation\ValidationFacade as V;

$fields    = Request::post()->all();
$processed = [
    'name'        => V::sanitize($fields['name'])->on
    'csrf'        => V::sanitize($fields['csrf'])->csrf(Session::get('csrf_token'))->run(),
];

if (V::approve($processed)) {
    $data = V::getValidated($processed, ['csrf', '_method']);
} else {
    $errors = V::getErrors($processed);
}

$router->resource('api/users', 'api/user', UserController::class);

$router->resource('api/posts', 'api/post', PostController::class, [
    'actionIndex',   // GET    api/posts       — list all posts
    'actionView',    // GET    api/post/:id    — get single post
    'actionAdd',     // POST   api/posts       — create new post
    'actionUpdate',  // PUT/PATCH api/post/:id — update post
    'actionDrop'     // DELETE api/post/:id    — delete post
]);

use Rudra\View\ViewFacade as View;

// Cache-first strategy with fallback
echo View::cache(['mainpage', '+1 day']) ?? View::render(['layout', 'mainpage'], [
    'content' => View::cache(["page_{$slug}", '+1 day']) 
        ?? View::view(['page', "page_{$slug}"], ['foo' => 'bar']),
]);

// Or with helpers
data(['content' => cache(['mainpage']) ?? view(['index', 'mainpage'])]);
render('layout', data());

namespace App\Containers\User\Entity;

use Rudra\Model\Entity;

class User extends Entity
{
    public static ?string $table = 'users';
}

// Usage — no Model or Repository needed:
// These methods are provided by the base Repository automatically
$users = User::getAll();
$user  = User::find(1);
User::create(['name' => 'John', 'email' => '[email protected]']);

namespace App\Containers\User\Repository;

use Rudra\Model\Repository;

class UserRepository extends Repository
{
    public function findActiveUsers(): array
    {
        return $this->qBuilder("SELECT * FROM {$this->table} WHERE active = 1");
    }
}

// Automatically routed:
$activeUsers = User::findActiveUsers();

use Rudra\Model\QBFacade as QB;

$query = QB::select('id, name, email')
    ->from('users')
    ->where('status = :status')
    ->and('role = :role')
    ->orderBy('created_at DESC')
    ->limit(10)
    ->get(); // Returns SQL query string

// Execute via Repository:
$results = User::qBuilder($query, ['status' => 'active', 'role' => 'admin']);

use Rudra\Model\Schema;

Schema::create('users', function ($table) {
    $table->integer('id', autoincrement: true)
          ->string('name')
          ->string('email')
          ->text('bio', 'NULL')
          ->createdAt()
          ->updatedAt()
          ->primaryKey('id'); // Explicitly declare primary key
})->execute();

// Cache the result of User::getAll() method
$users = User::cache(['getAll']);

// Cache Post::findBy('category', 'news') with 1 hour TTL
$posts = Post::cache(['findBy', ['category', 'news']], '+1 hour');

// Auto-clears on create/update/delete
bash
php rudra secret
bash
php rudra env
bash
php rudra serve
bash
php rudra make:container
bash
php rudra make:controller