PHP code example of luany / core

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

    

luany / core example snippets


$request = Request::fromGlobals();

$request->method();                          // 'GET'
$request->uri();                             // '/users/42'
$request->input('name', 'default');          // body or query value
$request->query('page');                     // query string only
$request->post('email');                     // body only
$request->all();                             // merged query + body$request->body();                            // body only$request->only(['name', 'email']);
$request->except(['password']);
$request->has('name');                       // bool
$request->filled('name');                    // bool — exists and non-empty
$request->file('avatar');                    // ?array
$request->hasFile('avatar');                 // bool
$request->header('Authorization');           // case-insensitive
$request->server('REMOTE_ADDR');
$request->cookie('app_locale', 'en');
$request->hasCookie('app_locale');
$request->ip();                              // X-Forwarded-For → REMOTE_ADDR
$request->userAgent();
$request->url();                             // full URL with scheme+host
$request->isGet(); $request->isPost();       // method shortcuts
$request->isMethod('DELETE');
$request->isAjax();
$request->expectsJson();

// Factories
Response::make('<h1>Hello</h1>', 200);
Response::json(['user' => $user]);
Response::json(['error' => 'Not found'], 404);
Response::redirect('/dashboard');
Response::redirect('/permanent', 301);
Response::notFound();
Response::unauthorized();
Response::forbidden();
Response::serverError();

// Fluent building
(new Response())
    ->status(422)
    ->body(json_encode(['errors' => $errors]))
    ->header('Content-Type', 'application/json')
    ->withHeaders(['X-Request-Id' => $id]);

// Inspection
$response->getStatusCode();  // int
$response->getBody();        // string
$response->getHeaders();     // array
$response->isRedirect();     // bool (3xx)
$response->isSuccessful();   // bool (2xx)

// Send to client (call once at end of lifecycle)
$response->send();

use Luany\Core\Routing\Route;

Route::get('/users',       [UserController::class, 'index']);
Route::post('/users',      [UserController::class, 'store']);
Route::put('/users/{id}',  [UserController::class, 'update']);
Route::patch('/users/{id}',[UserController::class, 'update']);
Route::delete('/users/{id}',[UserController::class, 'destroy']);
Route::any('/ping', fn() => Response::make('pong'));

// Closure actions
Route::get('/hello', function (Request $request) {
    return Response::make('Hello!');
});

Route::get('/users/{id}', [UserController::class, 'show']);
// Controller: public function show(Request $request, string $id): Response

Route::get('/posts/{post}/comments/{comment}', [CommentController::class, 'show']);
// Parameters passed in order of appearance. Never written to $_GET.

Route::get('/users/{id}', [UserController::class, 'show'])->name('users.show');

$url = Route::router()->getNamedRoute('users.show', ['id' => 42]);
// → '/users/42'

// Prefix
Route::prefix('/admin')->group(function () {
    Route::get('/dashboard', [AdminController::class, 'dashboard']); // → /admin/dashboard
});

// Middleware
Route::middleware(AuthMiddleware::class)->group(function () {
    Route::get('/profile', [ProfileController::class, 'show']);
});

// Combined shorthand
Route::group(['prefix' => '/api/v1', 'middleware' => [AuthMiddleware::class]], function () {
    Route::get('/users', [UserController::class, 'index']);
    Route::post('/users', [UserController::class, 'store']);
});

// Nested
Route::prefix('/api')->group(function () {
    Route::prefix('/v1')->group(function () {
        Route::get('/status', fn() => Response::json(['ok' => true]));
        // → /api/v1/status
    });
});

Route::resource('products', ProductController::class);
// GET    /products           → index
// GET    /products/create    → create
// POST   /products           → store
// GET    /products/{id}      → show
// GET    /products/{id}/edit → edit
// PUT    /products/{id}      → update
// PATCH  /products/{id}      → update
// DELETE /products/{id}      → destroy

Route::apiResource('posts', PostController::class);
// Same but without create/edit

Route::resource('users', UserController::class, ['only' => ['index', 'show']]);
Route::resource('users', UserController::class, ['except' => ['create', 'edit']]);

Route::setViewRenderer(fn($view, $data) => $engine->render($view, $data));

Route::view('/welcome', 'pages.welcome');
Route::view('/about', 'pages.about', ['title' => 'About Us']);

// Custom resolver
Route::bind('user', fn($id) => User::find($id));

// Shorthand — uses the model's static find() method
Route::model('post', Post::class);

// Action receives a resolved instance (or null if not found)
Route::get('/users/{user}', function (Request $request, ?User $user) {
    if ($user === null) {
        return Response::notFound();
    }
    return Response::json($user->toArray());
});

// In production bootstrap:
if (!Route::loadCache(base_path('storage/cache/routes.php'))) {
    te::clearCache(base_path('storage/cache/routes.php'));

use Luany\Core\Middleware\Pipeline;

$response = (new Pipeline())
    ->send($request)
    ->through([AuthMiddleware::class, LogMiddleware::class])
    ->then(fn(Request $req) => $controller->action($req));

use Luany\Core\Middleware\MiddlewareInterface;

class AuthMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, callable $next): Response
    {
        if (!isset($_SESSION['user_id'])) {
            return Response::redirect('/login');
        }
        return $next($request);
    }
}

use Luany\Core\Middleware\CorsMiddleware;

// Default — allow all origins (public API, no credentials)
$cors = new CorsMiddleware();

// Production — specific origins with credentials
$cors = new CorsMiddleware(
    allowedOrigins:   ['https://app.example.com', '*.staging.example.com'],
    allowedMethods:   ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders:   ['Content-Type', 'Authorization'],
    exposedHeaders:   ['X-Total-Count'],
    allowCredentials: true,
    maxAge:           3600,
);

use Luany\Core\Middleware\RateLimitMiddleware;
use Luany\Core\RateLimit\FileRateLimiter;

$limiter = new FileRateLimiter(base_path('storage/rate-limits'));

// On a route
Route::post('/login', [AuthController::class, 'login'])
    ->middleware(new RateLimitMiddleware($limiter, maxAttempts: 5, decaySeconds: 60));

use Luany\Core\RateLimit\InMemoryRateLimiter;

$limiter = new InMemoryRateLimiter();
$limiter->attempt('key', 5, 60);           // bool
$limiter->remaining('key', 5);             // int
$limiter->tooManyAttempts('key', 5);       // bool
$limiter->availableAt('key');              // int (Unix timestamp)
$limiter->reset('key');                    // void
InMemoryRateLimiter::flush();             // clear all keys (use in test tearDown)

use Luany\Core\RateLimit\FileRateLimiter;

$limiter = new FileRateLimiter(base_path('storage/rate-limits'));
$limiter->attempt('api:ip:127.0.0.1', 60, 60);
$limiter->reset('api:ip:127.0.0.1');
$limiter->flush(); // removes all rl_*.json files

interface RateLimiterInterface
{
    public function attempt(string $key, int $maxAttempts, int $decaySeconds): bool;
    public function remaining(string $key, int $maxAttempts): int;
    public function availableAt(string $key): int;
    public function tooManyAttempts(string $key, int $maxAttempts): bool;
    public function reset(string $key): void;
}

use Luany\Core\Exceptions\MethodNotAllowedException;
use Luany\Core\Exceptions\RouteNotFoundException;

// In your application's Exception Handler:
public function render(\Throwable $e): Response
{
    if ($e instanceof MethodNotAllowedException) {
        return Response::make('Method Not Allowed', 405)
            ->header('Allow', $e->getAllowHeaderValue());
    }
    if ($e instanceof RouteNotFoundException) {
        return Response::notFound();
    }
    return parent::render($e);
}