PHP code example of serwisant / serwisant-silex

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

    

serwisant / serwisant-silex example snippets



Serwisant\Silex;
use Symfony\Component\HttpFoundation\Request;

$app = new Silex\Application(['debug' => true]);

$app->register(new Silex\Provider\TwigServiceProvider(), ['twig.path' => __DIR__ . '/../views']);

$app->get('/', function (Silex\Application $app) {
  return $app->render('index.html.twig');
})->bind('home');

$app->get('/hello/{name}', function (Silex\Application $app, Request $request, $name) {
  return 'Hello ' . $app->escape($name);
});

$app->run();

$app = new Silex\Application(['debug' => true, 'env' => 'development']);
$app['my.option'] = 42;

$app->get('/agreements/{id}', function ($id) {
  return "Agreement no. $id";
})
  ->assert('id', '\d+')
  ->convert('id', fn($id) => (int)$id)
  ->bind('agreement');

$app->get('/blog/{page}', fn($page) => "Page $page")->value('page', 1);

$app->match('/contact', fn(Request $request) => $request->getMethod())->method('GET|POST');

// 1. callable – receives an empty collection
$app->mount('/api', function (Silex\ControllerCollection $api) {
  $api->get('/items', fn() => ['a' => 1]);           // GET /api/items
  $api->before(function (Request $request) {           // applies to all routes under /api
    // e.g. token check
  });
});

// 2. collection from the factory
$admin = $app['controllers_factory'];
$admin->get('/', fn() => 'panel')->bind('admin');     // GET /admin/
$admin->');
    return $blog;
  }
}
$app->mount('/blog', new BlogControllerProvider());

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

// before the controller; returning a Response skips the controller
$app->before(function (Request $request, Silex\Application $app) {
  if (!$request->cookies->has('token')) {
    return $app->redirect('/login');
  }
});

// after the controller; the response can be modified or a new one returned
$app->after(function (Request $request, Response $response, Silex\Application $app) {
  $response->headers->set('X-Frame-Options', 'DENY');
});

// after the response has been sent to the client (e.g. logging, sending e-mails)
$app->finish(function (Request $request, Response $response, Silex\Application $app) {
});

$app->get('/account', fn() => 'my account')
  ->before(function (Request $request, Silex\Application $app) {
    // returning a Response skips the controller
  })
  ->after(function (Request $request, Response $response, Silex\Application $app) {
  });

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

// only for 404 – the type of the first argument filters exceptions
$app->error(function (NotFoundHttpException $e, Request $request, int $code) use ($app) {
  return new Response($app->renderView('404.html.twig'), 404);
});

// all other errors, including PHP errors (TypeError etc.)
$app->error(function (\Throwable $e, Request $request, int $code) {
  if ($code >= 500) {
    \Sentry\captureException($e);
  }
  // no return – handling is passed on to the next handler or the default error page
});

// abort handling with an HTTP status code
$app->abort(404, 'Not found');

// arrays as JSON
$app->view(function (array $result, Request $request) use ($app) {
  return $app->json($result);
});

// date objects as text
$app->view(function (\DateTimeInterface $date) {
  return $date->format('Y-m-d');
});

$app->get('/api/status', fn() => ['status' => 'ok']);

// shared (single instance)
$app['mailer'] = function ($app) {
  return new Mailer($app['mailer.dsn']);
};

// new instance on every access
$app['form'] = $app->factory(fn($app) => new Form());

// closure as a value (not a factory)
$app['slugify'] = $app->protect(fn(string $s) => strtolower($s));

// extending an existing service
$app->extend('twig', function (\Twig\Environment $twig, $app) {
  $twig->addFilter(new \Twig\TwigFilter('upper', 'strtoupper'));
  return $twig;
});

$app->register(new Silex\Provider\TwigServiceProvider(), [
  'twig.path' => __DIR__ . '/views',               // string or array of paths; [path => 'name'] = namespace @name
  'twig.templates' => ['hello' => 'Hello {{ name }}'], // in-memory templates
  'twig.options' => ['cache' => __DIR__ . '/tmp/twig'],
]);

$app->register(new Silex\Provider\AssetServiceProvider(), [
  'assets.base_path' => '/assets',            // or 'assets.base_urls' => ['https://cdn.example.com']
  'assets.version' => 'v42',
  'assets.version_format' => '%s?version=%s', // result: /assets/css/style.css?version=v42
  // 'assets.json_manifest_path' => __DIR__ . '/public/manifest.json',  // instead of assets.version
  'assets.named_packages' => [
    'images' => ['base_urls' => ['https://img.example.com']],   // {{ asset('logo.png', 'images') }}
  ],
]);

$app->register(new Silex\Provider\SessionServiceProvider(), [
  'session.storage.options' => ['name' => 'SID', 'cookie_lifetime' => 0, 'cookie_secure' => true, 'cookie_httponly' => true, 'cookie_samesite' => 'lax'],
  'session.storage.save_path' => '/tmp/sessions',
]);

$app->post('/login', function (Request $request, Silex\Application $app) {
  $request->getSession()->set('user', 'john');   // or $app['session']->set(...)
  return $app->redirect('/');
});

$app->get('/', function (SessionInterface $session) {
  return 'Logged in as: ' . $session->get('user');
});

$app->register(new Silex\Provider\CorsServiceProvider(), [
  'cors.allowOrigin' => 'https://a.example.com https://b.example.com', // default '*' – any origin
  'cors.allowMethods' => ['GET', 'POST'],   // default: methods of the routes matching the path
  'cors.maxAge' => 15,
  'cors.allowCredentials' => false,
  'cors.exposeHeaders' => '',
]);

$app->register(new Silex\Provider\ServiceControllerServiceProvider());

$app['posts.controller'] = fn($app) => new PostsController($app['db']);

$app->get('/posts', 'posts.controller:indexAction');

use Pimple\Container;
use Pimple\ServiceProviderInterface;
use Serwisant\Silex\Api\BootableProviderInterface;
use Serwisant\Silex\Api\EventListenerProviderInterface;
use Serwisant\Silex\Application;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\KernelEvents;

class SecurityHeadersProvider implements ServiceProviderInterface, EventListenerProviderInterface, BootableProviderInterface
{
  public function register(Container $app): void
  {
    $app['security_headers'] = ['X-Frame-Options' => 'DENY'];
  }

  public function subscribe(Container $app, EventDispatcherInterface $dispatcher): void
  {
    $dispatcher->addListener(KernelEvents::RESPONSE, function ($event) use ($app) {
      $event->getResponse()->headers->add($app['security_headers']);
    });
  }

  public function boot(Application $app): void
  {
    // e.g. additional routes: $app->get('/health', fn() => 'OK');
  }
}

$app->register(new SecurityHeadersProvider(), ['security_headers' => ['X-Frame-Options' => 'SAMEORIGIN']]);

use Symfony\Component\HttpFoundation\Request;

$app = /5'));

assert($response->getStatusCode() === 200);
assert(str_contains($response->getContent(), 'Agreement'));