Silex Documentation

repository·master·Indexed 25 days ago

https://github.com/silexphp/silex

A PHP micro-framework built on top of Symfony components for developing websites and small-scale applications. Documentation includes guides on error handling with Symfony/Debug, custom authentication using Guard, JSON request and response handling, Monolog logger configuration, and database-backed session storage using PdoSessionHandler.

Tokens
40.3K
Snippets
145
Records
219
Agent score
86%

What's inside Silex

  1. Understand the Silex Application interface

    master

    The Application class is the primary entry point for Silex. It implements Symfony's HttpKernelInterface, meaning you can pass a Request object to the handle method to receive a Response object.

    Because Application extends the Pimple service container, you can use it to both read and replace any service within the application. It also utilizes the EventDispatcher to manage lifecycle events such as fetching the Request, converting string responses to Response objects, handling exceptions, and executing middleware (before/after events).

  2. Enable Stateless Authentication

    master

    For authentication methods where credentials are sent with every request (like HTTP authentication, WSSE, or certificates), you can disable session persistence by setting stateless to true in the firewall configuration.

    $app['security.firewalls'] = array(
        'default' => array(
            'stateless' => true,
            'wsse' => true,
            // ...
        ),
    );
  3. Use VarDumper for debugging

    master

    Once the VarDumperServiceProvider is registered and the symfony/var-dumper component is installed, you can use the following debugging tools:

    • PHP: Use the global dump() function anywhere in your code to inspect variables.
    • Twig: Use the dump() Twig function or the {% dump %} Twig tag to inspect variables within templates.
    • Web Profiler: If used alongside the Silex WebProfiler, dumps will be automatically made available in the web debug toolbar and the web profiler.
  4. Integrate Symfony Twig Bridge for advanced features

    master

    By installing symfony/twig-bridge, the TwigServiceProvider gains additional capabilities:

    Routing Functions

    Access path() and url() functions in templates:

    {{ path('homepage') }}
    {{ url('homepage') }} {# absolute URL #}
    {{ path('hello', {name: 'Fabien'}) }}

    Global Variable

    The global variable provides access to AppVariable methods:

    {{ global.request }}
    {{ global.user }}
    {{ global.session }}
    {{ global.debug }}
    {{ global.flashes }}

    Other Integrations

    • Translation: If TranslationServiceProvider is registered, use trans() and transchoice().
    • Forms: If FormServiceProvider is registered, use form helpers.
    • Security: If SecurityServiceProvider is registered, use is_granted().
    • Web Link: If symfony/web-link is installed, use preload(), prefetch(), prerender(), dns_prefetch(), preconnect(), and link().
    composer require symfony/twig-bridge
  5. Install the VarDumperServiceProvider

    master

    To use the VarDumperServiceProvider, you must first add the Symfony VarDumper Component to your project via Composer. Then, register the provider within your Silex application.

    composer require symfony/var-dumper
    $app->register(new Silex\Provider\VarDumperServiceProvider());
  6. Group controllers using ControllerCollection

    master

    To prevent your main application file from becoming cluttered, you can group related routes into logical collections using $app['controllers_factory']. This factory returns a new instance of ControllerCollection.

    Once a collection is defined, use the mount() method to attach it to the main application with a specific URL prefix. All routes defined within that collection will be prefixed with the provided path.

    // define controllers for a blog
    $blog = $app['controllers_factory'];
    $blog->get('/', function () {
        return 'Blog home page';
    });
    
    // define "global" controllers
    $app->get('/', function () {
        return 'Main home page';
    });
    
    // mount the collection with a prefix
    $app->mount('/blog', $blog);
  7. Install dependencies for AssetServiceProvider

    master

    To use the AssetServiceProvider, you must install the Symfony Asset Component. If you intend to use assets within Twig templates, you must also install the Symfony Twig Bridge.

    composer require symfony/asset
    # If using Twig templates:
    composer require symfony/twig-bridge
  8. Configure nginx for Silex

    master

    The minimum Nginx configuration requires setting the root to your project's web directory and using try_files to fallback to the front controller (index.php).

    Key configuration details:

    • Use try_files $uri /index.php$is_args$args; in the / location block.
    • Use a specific location block for index.php to handle FastCGI.
    • If you use separate front controllers for development and production, adjust the location regex to ~ ^/(index|index_dev)\.php(/|$).
    • To prevent URIs that include the front controller (e.g., domain.tld/index.php/some-path) from working, add the internal; directive inside the PHP location block.
    • A catch-all location block for \.php$ should return a 404 to ensure all PHP requests are handled by the front controller.
    server {
        server_name domain.tld www.domain.tld;
        root /var/www/project/web;
    
        location / {
            # try to serve file directly, fallback to front controller
            try_files $uri /index.php$is_args$args;
        }
    
        # If you have 2 front controllers for dev|prod use the following line instead
        # location ~ ^/(index|index_dev)\.php(/|$) {
        location ~ ^/index\.php(/|$) {
            # the ubuntu default
            fastcgi_pass   unix:/var/run/php/phpX.X-fpm.sock;
            # for running on centos
            #fastcgi_pass   unix:/var/run/php-fpm/www.sock;
    
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param HTTPS off;
    
            # Prevents URIs that include the front controller. This will 404:
            # http://domain.tld/index.php/some-path
            # Enable the internal directive to disable URIs like this
            # internal;
        }
    
        #return 404 for all php files as we do have a front controller
        location ~ \.php$ {
            return 404;
        }
    
        error_log /var/log/nginx/project_error.log;
        access_log /var/log/nginx/project_access.log;
    }
  9. Configure Apache for Silex

    master

    To use Apache, ensure mod_rewrite is enabled. You can use a .htaccess file in your application directory to route requests to index.php.

    If your application is not located at the webroot level, you must uncomment the RewriteBase statement in the .htaccess and adjust the path relative to the webroot.

    Alternatively, for Apache 2.2.16 or higher, you can use the simpler FallbackResource directive in your .htaccess or within a <VirtualHost> configuration.

    <IfModule mod_rewrite.c>
        Options -MultiViews
    
        RewriteEngine On
        #RewriteBase /path/to/app
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.php [QSA,L]
    </IfModule>