PHP code example of jasny / controller

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

    

jasny / controller example snippets


class MyController extends Jasny\Controller\Controller
{
    public function hello(string $name, #[QueryParam] string $others = ''): void
    {
        $this->output("Hello $name" . ($others ? " and $others" : ""), 'text');
    }
}

use Jasny\Controller\Middleware\Slim as ControllerMiddleware;
use Slim\Factory\AppFactory;

$app = AppFactory::create();

$app->add(new ControllerMiddleware());
$app->addRoutingMiddleware();

$app->get('/hello/{name}', ['MyController', 'hello']);

use Jasny\Controller\Middleware\Slim as ControllerMiddleware;
use Slim\Factory\AppFactory;

$app = AppFactory::create();

$app->add(new ControllerMiddleware(true));
$app->addRoutingMiddleware();
$app->addErrorMiddleware(true, true, true);

$stud = fn($str) => strtr(ucwords($str, '-'), ['-' => '']);

$invoker = new Invoker(fn (?string $controller, ?string $action) => [
    $controller !== null ? $stud($controller) . 'Controller' : $stud($action) . 'Action',
    '__invoke'
]);

$this->output('Hello world');

class MyController extends Jasny\Controller\Controller
{
    /**
     * Output a random number between 0 and 100 as HTML
     */
    public function random()
    {
        $number = rand(0, 100);
        $this->output("<h1>$number</h1>", 'html');
    }
}

class MyController extends Jasny\Controller\Controller
{
    /**
     * Output 5 random numbers between 0 and 100 as JSON
     */
    public function random()
    {
        $numbers = array_map(fn() => rand(0, 100), range(1, 5));
        $this->json($numbers);
    }
}

class MyController extends Jasny\Controller\Controller
{
    public function process(string $size)
    {
        if (!in_array($size, ['XS', 'S', 'M', 'L', 'XL'])) {
            return $this
                ->status("400 Bad Request")
                ->output("Invalid size: $size");
        }

        // Create something ...
        
        return $this
            ->status(201)
            ->header("Location: http://www.example.com/foo/something")
            ->json($something);
    }
}

class MyController extends Jasny\Controller\Controller
{
    public function process(string $size)
    {
        if (!in_array($size, ['XS', 'S', 'M', 'L', 'XL'])) {
            return $this->badRequest()->output("Invalid size: $size");
        }

        // Create something ...
        
        return $this
            ->created("http://www.example.com/foo/something")
            ->json($something);
    }
}

class MyController extends Jasny\Controller\Controller
{
    public function process()
    {
        $this->header("Content-Language", "nl");
        // ...
    }
}

$this->header("Cache-Control", "no-cache"); // overwrite header
$this->header("Cache-Control", "no-store", true); // add header

$app->get('/hello/{name}', ['MyController', 'hello']);

class MyController extends Jasny\Controller\Controller
{
    public function hello(string $name)
    {
        $this->output("Hello $name");
    }
}

use Jasny\Controller\Controller;
use Jasny\Controller\Parameter\PathParam;
use Jasny\Controller\Parameter\QueryParam;

class MyController extends Controller
{
    public function hello(#[PathParam] string $name, #[QueryParam('and')] string $other = '')
    {
        $this->output("Hello $name" . ($other ? " and $other" : ""));
    }
}

use Jasny\Controller\Controller;
use Jasny\Controller\Parameter\BodyParam;

class MyController extends Controller
{
    public function send(#[BodyParam(type: 'email')] string $emailAddress)
    {
        // ...
    }
}

use Jasny\Controller\Controller;
use Jasny\Controller\Parameter\PostParam;

class MyController extends Controller
{
    public function message(#[PostParam(type: 'email')] array $email)
    {
        // ...
    }
}

use Jasny\Controller\Parameter\SingleParameter;

SingleParameter::$types['slug'] = [FILTER_VALIDATE_REGEXP, '/^[a-z\-]+$/'];

class MyController extends Jasny\Controller\Controller
{
    public function hello()
    {
        $language = $this->negotiateLanguage(['en', 'de', 'fr', 'nl;q=0.6']);
        
        switch ($language) {
            case 'en':
                return $this->output('Good morning');
            case 'de':
                return $this->output('Guten Morgen');
            case 'fr':
                return $this->output('Bonjour');
            case 'nl':
                return $this->output('Goedemorgen');
            default:
                return $this
                    ->notAcceptable()
                    ->output("This content isn't available in your language");
        }
    }
}

class MyController extends Jasny\Controller\Controller
{
    protected function before()
    {
        if ($this->auth->getUser()->getCredits() <= 0) {
            return $this->paymentRequired()->output("Sorry, you're out of credits");
        }
    }

    // ...
}

class MyController extends Jasny\Controller\Controller
{
    // ...
    
    protected function after()
    {
        $this->header('X-Available-Credits', $this->auth->getUser()->getCredits());
    }
}

class MyController extends Jasny\Controller\Controller
{
    #[MustBeLoggedIn]
    public function send()
    {
        // ...
    }
}

use Jasny\Controller\Guard;
use Jasny\Controller\Parameter\Attr;

#[\Attribute]
class MustBeLoggedIn extends Guard
{
    public function process(#[Attr] User? $sessionUser)
    {
        if ($sessionUser === null) {
            return $this->forbidden()->output("Not logged in");
        }
    }
}

#[MinimalCredits(value: 20)]
class MyController extends \Jasny\Controller\Controller
{
    // ...
}

use Jasny\Controller\Guardian;
use Jasny\Controller\Guard;
use DI\Container;

return [
    Guardian::class => function (Container $container) {
        return new class ($container) extends Guardian {
            public function __construct(private Container $container) {}
            
            public function instantiate(\ReflectionAttribute $attribute): Guard {
                $guard = $attribute->newInstance();
                $this->container->injectOn($guard);
                
                return $guard;
            }
        } 
    }
];

use Jasny\Controller\Guard;
use DI\Attribute\Inject;

class MyGuard extends Guard
{
    #[Inject]
    private DBConnection $db;
    
    // ...
}

use Jasny\Controller\Controller;
use Jasny\Controller\Guardian;

class MyController extends Controller
{
    public function __construct(
        protected Guardian $guardian
    ) {}
}