PHP code example of michaelyousrie / batframe

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

    

michaelyousrie / batframe example snippets


use Batframe\Batframe;
use Batframe\Http\Request;
use Batframe\Http\Response;

class App extends Batframe
{
    public function index()                     // GET /
    {
        return view('home', ['name' => 'World']);
    }

    public function getUsers()                  // GET /users
    {
        return ['users' => ['ada', 'linus']];   // arrays become JSON automatically
    }

    public function getUser(int $id)            // GET /user/{id}
    {
        return ['id' => $id];
    }

    public function postUsers(Request $request) // POST /users
    {
        return Response::json(['created' => $request->input('name')], 201);
    }
}

(new App())->run();

trait UserRoutes
{
    public function getUsers()          { /* GET /users */ }
    public function getUser(int $id)    { /* GET /user/{id} */ }
    public function postUsers()         { /* POST /users */ }

    // verbless helper — shared by the routes above, not itself a route
    protected function formatName(string $name): string { /* ... */ }
}

class App extends Batframe
{
    use UserRoutes;
    use PageRoutes;
}

$request->input('name', $default); // JSON body, then form body, then query string
$request->get('q');                // single value from the query string (GET data)
$request->query('q');              // single query param (alias of get())
$request->post('name');            // single value from the body (form OR JSON)
$request->form('name');            // form body only (never the JSON body)
$request->json('name');            // JSON body only (never the form body)
$request->allGet();                // every GET/query param as an array
$request->allQuery();              // alias of allGet()
$request->allPost();               // whole body as an array (form + JSON merged)
$request->all();                   // everything merged (query + body + JSON)
$request->only('name', 'email');   // just those inputs
$request->except('password');      // everything but those
$request->filled('name');          // present and not empty ("0" counts)
$request->boolean('active');       // "1"/"true"/"on"/"yes" => true
$request->integer('page', 1);      // cast with a fallback
$request->string('q');             // cast with a fallback
$request->json();                  // decoded JSON body as an array
$request->header('Authorization'); // case-insensitive
$request->bearerToken();           // Bearer token, or null
$request->method();                // "GET"
$request->path();                  // "/users"
$request->wantsJson();             // content negotiation
$request->ip();

request();               // the Batframe\Http\Request instance
request('name');         // input from the query string or the body
request('page', 1);      // with a fallback
request()->only('a', 'b');

Response::json($data, 200);
Response::html('<h1>Hi</h1>');
Response::text('plain');
Response::view('home', ['name' => 'World']);   // rendered through the view engine
Response::redirect('/login');
Response::file('/path/to/file.pdf');
Response::noContent();

// fluent
Response::json($data)->status(201)->header('X-Trace', 'abc');

session()->put('user_id', 42);
$id = session('user_id');              // 42
session(['theme' => 'dark', 'lang' => 'en']); // set several at once

session()->has('user_id');             // present and not null
session()->pull('cart');               // read and remove
session()->forget('user_id');
session()->push('items', $item);       // append to an array value
session()->increment('visits');        // handy counters
session()->flush();                    // clear everything

// flash data lives for the next request only
session()->flash('status', 'Saved!');
$status = session('status');

session()->regenerate();               // new id, e.g. after login
session()->destroy();                  // end the session

cache()->put('report', $data, 3600);   // expires in an hour
cache()->forever('config', $config);   // never expires
$data = cache('report');               // read, or null when missing/stale
$data = cache('report', $fallback);    // read with a default

cache(['a' => 1, 'b' => 2], 600);      // write several at once, ttl in seconds
cache()->add('lock', 1, 30);           // write only if absent (returns bool)
cache()->has('report');                // present and not expired
cache()->pull('report');               // read and remove
cache()->increment('hits');            // handy counters (ttl preserved)
cache()->forget('report');
cache()->flush();                      // clear everything

// compute on miss, then cache for 10 minutes
$users = cache()->remember('users', 600, fn () => load_users());
$config = cache()->rememberForever('config', fn () => load_config());

use Batframe\Validation\Rule;

validate($email, [Rule:: string length 3 -> passes

// validate many values at once: the key is the value, the value is its rules
validateMany([
    '[email protected]' => [Rule::equest()->validate('name', [Rule::

new App([
    'base_path' => __DIR__ . '/..',
    'views'     => 'resources/views',
    'pages'     => 'resources/pages',
    'cache'     => 'storage/cache',
    'debug'     => true,
]);


(new App())->run();

use Batframe\Http\HttpException;

throw new HttpException(403, 'Forbidden');
abort(404);