PHP code example of preflow / core

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

    

preflow / core example snippets


// Bind an interface to a concrete class (transient)
$container->bind(CacheInterface::class, RedisCache::class);

// Bind as singleton (binding it again later replaces an instance already resolved)
$container->singleton(LoggerInterface::class, FileLogger::class);

// Or mark a class: shared from its first autowired get(), whoever asks first
#[\Preflow\Core\Container\Attributes\Singleton]
final class Registry {}

// Register a pre-built instance
$container->instance(Config::class, $config);

// Resolve (autowires constructor dependencies)
$service = $container->get(MyService::class);

// Instantiate with parameter overrides
$obj = $container->make(MyService::class, ['timeout' => 30]);

use Preflow\Core\Container\Attributes\Config;
use Preflow\Core\Container\Attributes\Env;

final class Mailer
{
    public function __construct(
        #[Config('mail.from')]
        private string $fromAddress,

        #[Config('mail.driver', default: 'smtp')]
        private string $driver,

        #[Env('MAIL_HOST')]
        private string $host,

        #[Env('MAIL_PORT', default: '587')]
        private string $port,
    ) {}
}

$config = new Config([
    'app' => ['name' => 'MyApp', 'debug' => false],
    'db'  => ['host' => 'localhost'],
]);

$config->get('app.name');          // 'MyApp'
$config->get('missing', 'fallback'); // 'fallback'
$config->has('db.host');           // true
$config->set('app.debug', true);
$config->all();                    // full array

use Preflow\Core\Container\Container;
use Preflow\Core\Container\ServiceProvider;

final class CacheServiceProvider extends ServiceProvider
{
    public function register(Container $container): void
    {
        $container->singleton(CacheInterface::class, RedisCache::class);
    }

    public function boot(Container $container): void
    {
        // Runs after all providers are registered
        $container->get(CacheInterface::class)->connect();
    }
}

$app->registerProvider(new CacheServiceProvider());

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final class AuthMiddleware implements MiddlewareInterface
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler,
    ): ResponseInterface {
        if (!$request->hasHeader('Authorization')) {
            return new Response(401);
        }

        return $handler->handle($request);
    }
}

$app->addMiddleware(new AuthMiddleware());

$app = Application::create([
    'app' => [
        'name'  => 'MyApp',
        'debug' => (bool) getenv('APP_DEBUG'),
    ],
]);

$app->registerProvider(new CacheServiceProvider());
$app->addMiddleware(new AuthMiddleware());
$app->setRouter($router);
$app->setActionDispatcher($dispatcher);
$app->setComponentRenderer($renderer);

$app->boot();

$response = $app->handle($request);

public function boot(Container $container): void
{
    $app = $container->get(Application::class);
    if ($app->runningInConsole()) {
        // Commands handle no request: set up once every provider booted.
        $app->onProvidersBooted(fn () => $this->setUpAdmin($container));
        return;
    }
    $app->onRequest(function (ServerRequestInterface $request) use ($container): void {
        if (str_starts_with($request->getUri()->getPath(), '/admin/')) {
            $this->setUpAdmin($container);  // make it idempotent: it runs on every such request
        }
    });
}

use Preflow\Core\Http\Middleware\JsonBodyMiddleware;

$app->addMiddleware(new JsonBodyMiddleware());

// In a controller:
$data = $request->getParsedBody(); // already a decoded array

use Preflow\Core\Flash\FlashType;

flashSuccess('Post saved.');
flashError('Validation failed.');
flashInfo('Changes are pending review.');
flashWarning('Disk space is low.');

// In a controller or template resolver:
$flashes = getFlashes(); // ['success' => ['Post saved.'], ...]

// config/middleware.php
return [
    Preflow\Core\Http\Middleware\JsonBodyMiddleware::class,
    App\Http\Middleware\LocaleMiddleware::class,
];

$throttle = $container->get(\Preflow\Core\Throttle\Throttle::class);
$client = $throttle->client($request);                    // salted hash, never the IP

if ($throttle->tooMany('login', $client, max: 5, windowSeconds: 600)) {
    // answer 429
}
$throttle->hit('login', $client, windowSeconds: 600);     // after a failed attempt
$throttle->clear('login', $client);                       // after a success

use Preflow\Core\Http\Csrf\CsrfExempt;
use Preflow\Routing\Attributes\Post;
use Preflow\Routing\Attributes\Route;

#[Route('/hooks')]
#[CsrfExempt('Stripe webhook, verified by its signature')]
final class StripeWebhookController
{
    #[Post('/stripe')]
    public function receive(ServerRequestInterface $request): ResponseInterface { /* … */ }
}

return [
    'exempt' => [],          // path prefixes without a check, added to '/--component/'
    'trusted_origins' => [], // other origins allowed to post, e.g. 'https://stage.example.com'
    'sign_in_paths' => [],   // sign-in forms of the site; packages register their own
];

   $container->get(\Preflow\Core\Http\Csrf\CsrfSignInPaths::class)->add('/shop/login');
   

use Preflow\Core\Http\Csrf\ExpiredSessionHandler;
use Preflow\Core\Http\Session\SessionInterface;

final class KeepDraftOnExpiry implements ExpiredSessionHandler
{
    public function handle(ServerRequestInterface $request): ?ResponseInterface
    {
        $path = $request->getUri()->getPath();
        if (!preg_match('#^/account/posts/\d+/edit$#D', $path)) {
            return null; // the framework's answer
        }
        // Keep the values to PREFILL the form after sign-in; never save them from here.
        $request->getAttribute(SessionInterface::class)
            ->set('draft:' . $path, (array) $request->getParsedBody());

        return new Response(303, ['Location' => '/login?next=' . rawurlencode($path)]);
    }
}

// in a ServiceProvider::register()
$container->singleton(ExpiredSessionHandler::class, KeepDraftOnExpiry::class);

use Preflow\Core\Application;
use Preflow\Core\Cache\CacheRegistry;
use Preflow\Core\Cache\DirectoryCache;
use Preflow\Core\Cache\FileCache;

final class SiteCacheProvider extends ServiceProvider
{
    public function register(Container $container): void
    {
        $app = $container->get(Application::class);
        $caches = $container->get(CacheRegistry::class);

        // A folder of cache files; the folder and dotfiles stay, symlinks inside it are never
        // followed. `pattern` is an fnmatch() pattern on file names; files matching `exclude` are
        // neither counted nor cleared.
        $caches->register(new DirectoryCache('site.thumbs', 'Thumbnails', $app->basePath('storage/cache/thumbs')));

        // A single file.
        $caches->register(new FileCache('site.sitemap', 'Sitemap', $app->basePath('storage/cache/sitemap.xml')));
    }
}

// config/page_cache.php: every key is optional, these are the defaults
return [
    'enabled' => false,
    'max_age' => 14400,              // seconds; older pages are rebuilt behind the next visitor; at most 72000 (20 h), 0 means that
    'rebuild_budget' => 2.0,         // seconds of rebuilding after a response
    'cache_query' => true,           // cache pages with a query string (search, filters)
    'ignore_query' => ['utm_*', 'fbclid', 'gclid', 'mc_cid', 'mc_eid'],
    'vary_headers' => ['HX-Request', 'HX-Target', 'HX-History-Restore-Request'], // plus the hypermedia clients' own varyHeaders()
    'signed_in_cookies' => [],       // added to the auth marker and the remember cookies
    'hosts' => [],                   // hosts cached besides the host of app.url
    'max_query_variants' => 50,      // pages with a query kept per URL path, oldest evicted first
    'max_pages' => 50000,            // pages kept in all, oldest evicted first
    'explain' => false,              // send X-Page-Cache-Skip (why a miss was not stored)
    'verify' => 'first',             // 'first', 'always' or 'off': render a page twice before storing it
];

  $pageCache = $container->get(\Preflow\Core\PageCache\PageCache::class);
  $pageCache->changed('default:member');      // the member table changed (many rows)
  $pageCache->changed('default:member#42');   // one member
  $pageCache->changed('*');                   // everything
  

  // config/auth.php
  'session' => [
      'paths' => ['/login', '/logout', '/account', '/folio', '/--component'],
      // ...
  ],
  

  $pageCache->isolate(static function () use ($content): \Closure {
      $restore = $content->showPublished();   // and empty the memos
      return $restore;                         // run after the render, last entered first
  });
  $pageCache->refuseWhen('working-copy', static fn (): bool => $content->showsDrafts());
  

  $container->get(\Preflow\Core\PageCache\PerRequestValues::class)
      ->register('form_token', fn (): string => FormToken::value());
  

  #[\Preflow\Components\Freshness(Freshness::NextVisit)]           // around resolveState() and render
  #[\Preflow\Components\Freshness(Freshness::Timed, seconds: 43200)]
  $pageCache->within(Freshness::NextVisit, null, fn () => $jobs->ofCompany($id));
  

use Preflow\Core\Exceptions\NotFoundHttpException;
use Preflow\Core\Exceptions\ForbiddenHttpException;
use Preflow\Core\Exceptions\UnauthorizedHttpException;

throw new NotFoundHttpException('Page not found');
throw new ForbiddenHttpException();
throw new UnauthorizedHttpException('Login 

use Preflow\Core\Http\NonPublicPaths;

if ($container->bound(NonPublicPaths::class)) {
    $container->get(NonPublicPaths::class)->add('/api');
}

use Preflow\Core\Http\SafeReturnPath;

$to = SafeReturnPath::check($request->getQueryParams()['next'] ?? null, ['/employer']) ?? '/employer';

#[Route('/jobs')]
final class JobPageController
{
    public function __construct(private readonly PageResponder $pages, private readonly DataManager $dm) {}

    #[Get('/{id}')]
    public function show(ServerRequestInterface $request): ResponseInterface
    {
        $job = $this->dm->find(Job::class, $request->getAttribute('id'));

        return $job === null
            ? $this->pages->render('_views/not-found.twig', status: 404)
            : $this->pages->render('_views/job.twig', ['job' => $job]);
    }
}

use App\Models\Job;   // your model, with public $uuid and $title
use Preflow\Auth\Http\TokenAuthMiddleware;
use Preflow\Core\Http\Json;
use Preflow\Data\DataManager;
use Preflow\Routing\Attributes\{Get, Middleware, Post, Route};
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

#[Route('/api/jobs')]
final class JobController
{
    public function __construct(private readonly DataManager $dm) {}

    #[Get('/')]
    public function index(): ResponseInterface
    {
        $jobs = $this->dm->query(Job::class)->get()
            ->map(fn (Job $j) => ['id' => $j->uuid, 'title' => $j->title])
            ->items();

        return Json::data($jobs, ['page' => 1]);
    }

    #[Post('/')]
    #[Middleware(TokenAuthMiddleware::class)]
    public function create(ServerRequestInterface $request): ResponseInterface
    {
        $job = new Job();
        $job->title = (string) ($request->getParsedBody()['title'] ?? '');

        // A failed validation throws ValidationException: the client gets the 422 shape below.
        $this->dm->save($job);

        return Json::data(['id' => $job->uuid], status: 201);
    }
}

return [
    'prefixes' => ['/api'],        // path prefixes (whole segments) that are the API
    'cors' => [
        'origins' => ['https://app.example.com'],   // empty (default) = CORS off; ['*'] = any
        'methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
        'headers' => ['Authorization', 'Content-Type', 'Accept'],
        'expose' => [],            // response headers a browser may read
        'max_age' => 600,          // seconds a preflight answer may be cached
        'credentials' => false,    // cannot be true together with origins ['*']
    ],
];
cron
    * * * * * cd /path/to/site/current && php preflow pages:work >/dev/null 2>&1