### Basic Silex Application Setup
Source: https://github.com/silexphp/silex/blob/master/doc/intro.rst
This snippet demonstrates the fundamental setup of a Silex application. It includes bootstrapping the framework, defining a simple GET route with a dynamic parameter, and running the application. This is the starting point for most Silex projects.
```php
get('/hello/{name}', function ($name) use ($app) {
return 'Hello '.$app->escape($name);
});
$app->run();
```
--------------------------------
### Install Silex Skeleton
Source: https://github.com/silexphp/silex/blob/master/doc/usage.rst
Installs the Silex Skeleton project using Composer for a quick start.
```bash
composer create-project fabpot/silex-skeleton path/to/install "~2.0"
```
--------------------------------
### Example Custom Provider Implementation
Source: https://github.com/silexphp/silex/blob/master/doc/providers.rst
An example demonstrating a custom provider that implements `ServiceProviderInterface`, `BootableProviderInterface`, and `EventListenerProviderInterface`.
```php
namespace Acme;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
use Silex\Application;
use Silex\Api\BootableProviderInterface;
use Silex\Api\EventListenerProviderInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\KernelEvents;
```
--------------------------------
### HelloControllerProvider Example
Source: https://github.com/silexphp/silex/blob/master/doc/providers.rst
An example implementation of the ControllerProviderInterface. This provider defines a simple route that redirects to '/hello'.
```php
namespace Acme;
use Silex\Application;
use Silex\Api\ControllerProviderInterface;
class HelloControllerProvider implements ControllerProviderInterface
{
public function connect(Application $app)
{
// creates a new controller based on the default route
$controllers = $app['controllers_factory'];
$controllers->get('/', function (Application $app) {
return $app->redirect('/hello');
});
return $controllers;
}
}
```
--------------------------------
### Swiftmailer Plugins Example
Source: https://github.com/silexphp/silex/blob/master/doc/providers/swiftmailer.rst
An example of how to add SwiftMailer plugins to the SwiftmailerServiceProvider configuration.
```php
$app['swiftmailer.plugins'] = function ($app) {
return array(
new \Swift_Plugins_PopBeforeSmtpPlugin('pop3.example.com'),
);
};
```
--------------------------------
### User Login Example
Source: https://github.com/silexphp/silex/blob/master/doc/providers/session.rst
An example of handling user login and setting session data using the session service.
```php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$app->get('/login', function (Request $request) use ($app) {
$username = $request->server->get('PHP_AUTH_USER', false);
$password = $request->server->get('PHP_AUTH_PW');
if ('igor' === $username && 'password' === $password) {
$app['session']->set('user', array('username' => $username));
return $app->redirect('/account');
}
$response = new Response();
$response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', 'site_login'));
$response->setStatusCode(401, 'Please sign in.');
return $response;
});
```
--------------------------------
### Basic Firewall Configuration with RequestMatcher
Source: https://github.com/silexphp/silex/blob/master/doc/providers/security.rst
Configures a security firewall named 'admin' that matches requests to paths starting with '/admin' and originating from 'example.com' using the POST method. This is a foundational setup for protecting specific URL patterns.
```php
use Symfony\Component\HttpFoundation\RequestMatcher;
$app['security.firewalls'] = array(
'admin' => array(
'pattern' => new RequestMatcher('^/admin', 'example.com', 'POST'),
// ...
),
);
```
--------------------------------
### Install Silex with Composer
Source: https://github.com/silexphp/silex/blob/master/README.rst
Installs the Silex framework version 2.0 using Composer, the dependency manager for PHP.
```bash
composer require silex/silex "~2.0"
```
--------------------------------
### Define a GET Route in Silex
Source: https://github.com/silexphp/silex/blob/master/doc/usage.rst
Example of defining a GET route in Silex that returns a list of blog post titles.
```php
$blogPosts = array(
1 => array(
'date' => '2011-03-29',
'author' => 'igorw',
'title' => 'Using Silex',
'body' => '...',
),
);
$app->get('/blog', function () use ($blogPosts) {
$output = '';
foreach ($blogPosts as $post) {
$output .= $post['title'];
$output .= '
';
}
return $output;
});
```
--------------------------------
### Swiftmailer SMTP Options Example
Source: https://github.com/silexphp/silex/blob/master/doc/providers/swiftmailer.rst
An example of how to configure the SMTP options for the SwiftmailerServiceProvider.
```php
$app['swiftmailer.options'] = array(
'host' => 'host',
'port' => '25',
'username' => 'username',
'password' => 'password',
'encryption' => null,
'auth_mode' => null
);
```
--------------------------------
### Installing Symfony Browser Kit and Css Selector
Source: https://github.com/silexphp/silex/blob/master/doc/testing.rst
Command to install necessary Symfony components for using the WebTestCase.
```bash
composer require --dev symfony/browser-kit symfony/css-selector
```
--------------------------------
### Account Access Example
Source: https://github.com/silexphp/silex/blob/master/doc/providers/session.rst
An example of accessing session data to check user authentication and display user information.
```php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$app->get('/account', function () use ($app) {
if (null === $user = $app['session']->get('user')) {
return $app->redirect('/login');
}
return "Welcome {$user['username']}!";
});
```
--------------------------------
### Silex Test Case Example
Source: https://github.com/silexphp/silex/blob/master/doc/testing.rst
An example of a Silex test class extending WebTestCase. It demonstrates how to create the Silex application instance and define test methods.
```php
namespace YourApp\Tests;
use Silex\WebTestCase;
class YourTest extends WebTestCase
{
public function createApplication()
{
return require __DIR__.'/../../../app.php';
}
public function testFooBar()
{
...
}
}
```
--------------------------------
### Install Serializer Component
Source: https://github.com/silexphp/silex/blob/master/doc/providers/serializer.rst
Installs the Symfony Serializer Component using Composer, a dependency for the SerializerServiceProvider.
```bash
composer require symfony/serializer
```
--------------------------------
### Define a Dynamic GET Route in Silex
Source: https://github.com/silexphp/silex/blob/master/doc/usage.rst
Example of defining a GET route with a dynamic ID parameter to display individual blog posts.
```php
$app->get('/blog/{id}', function (Silex\Application $app, $id) use ($blogPosts) {
if (!isset($blogPosts[$id])) {
$app->abort(404, "Post $id does not exist.");
}
$post = $blogPosts[$id];
return "
{$post['body']}
"; }); ``` -------------------------------- ### HelloServiceProvider Example Source: https://github.com/silexphp/silex/blob/master/doc/providers.rst Demonstrates the implementation of a Silex Service Provider that registers a 'hello' service. This service is a protected closure that returns a greeting, optionally using a default name. ```php use Symfony\Component\HttpKernel\Event\FilterResponseEvent; class HelloServiceProvider implements ServiceProviderInterface, BootableProviderInterface, EventListenerProviderInterface { public function register(Container $app) { $app['hello'] = $app->protect(function ($name) use ($app) { $default = $app['hello.default_name'] ? $app['hello.default_name'] : ''; $name = $name ?: $default; return 'Hello '.$app->escape($name); }); } public function boot(Application $app) { // do something } public function subscribe(Container $app, EventDispatcherInterface $dispatcher) { $dispatcher->addListener(KernelEvents::REQUEST, function(FilterResponseEvent $event) use ($app) { // do something }); } } ``` -------------------------------- ### Run Silex Tests Source: https://github.com/silexphp/silex/blob/master/README.rst Executes the test suite for Silex. This requires Composer to install dependencies and PHPUnit for running the tests. ```bash composer install phpunit ``` -------------------------------- ### Basic Silex Application Source: https://github.com/silexphp/silex/blob/master/README.rst A minimal Silex application demonstrating a simple GET route that greets a user. It requires the Composer autoloader and uses the SilexApplication class. ```php get('/hello/{name}', function ($name) use ($app) { return 'Hello '.$app->escape($name); }); $app->run(); ``` -------------------------------- ### Registering DoctrineServiceProvider Source: https://github.com/silexphp/silex/blob/master/doc/providers/doctrine.rst Demonstrates how to register the DoctrineServiceProvider with a single SQLite database connection. Requires the Doctrine DBAL library to be installed via Composer. ```php $app->register(new Silex\Provider\DoctrineServiceProvider(), array( 'db.options' => array( 'driver' => 'pdo_sqlite', 'path' => __DIR__.'/app.db', ), )); ``` ```bash composer require "doctrine/dbal:~2.2" ``` -------------------------------- ### Silex Custom User Provider Example Source: https://github.com/silexphp/silex/blob/master/doc/providers/security.rst Provides an example of a custom User Provider implementation using Doctrine DBAL to load user data from a database. ```php use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\User; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Doctrine\DBAL\Connection; class UserProvider implements UserProviderInterface { private $conn; public function __construct(Connection $conn) { $this->conn = $conn; } public function loadUserByUsername($username) { $stmt = $this->conn->executeQuery('SELECT * FROM users WHERE username = ?', array(strtolower($username))); if (!$user = $stmt->fetch()) { throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username)); } return new User($user['username'], $user['password'], explode(',', $user['roles']), true, true, true, true); } public function refreshUser(UserInterface $user) { if (!$user instanceof User) { throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); } return $this->loadUserByUsername($user->getUsername()); } public function supportsClass($class) { return $class === 'Symfony\Component\Security\Core\User\User'; } } ``` -------------------------------- ### Installing Symfony Asset Component Source: https://github.com/silexphp/silex/blob/master/doc/providers/asset.rst Instructions for adding the Symfony Asset Component as a project dependency using Composer. ```bash composer require symfony/asset ``` -------------------------------- ### Silex Firewall Configuration Example Source: https://github.com/silexphp/silex/blob/master/doc/providers/security.rst Demonstrates how to define firewall configurations in Silex, including patterns for URL matching, disabling security for specific routes, and enabling WSSE authentication. ```php $app['security.firewalls'] = array( 'api' => array( 'pattern' => '^/api', 'security' => $app['debug'] ? false : true, 'wsse' => true, // ... ), ); ``` -------------------------------- ### Installing Symfony Twig Bridge Source: https://github.com/silexphp/silex/blob/master/doc/providers/asset.rst Instructions for installing the Symfony Twig Bridge using Composer, which is required for using assets in Twig templates. ```bash composer require symfony/twig-bridge ``` -------------------------------- ### Example API Request and Response Source: https://github.com/silexphp/silex/blob/master/doc/cookbook/json_request_body.rst Demonstrates the structure of an HTTP request with a JSON body and the corresponding JSON response for creating a blog post. ```text POST /blog/posts Accept: application/json Content-Type: application/json Content-Length: 57 {"title":"Hello World!","body":"This is my first post!"} ``` ```text HTTP/1.1 201 Created Content-Type: application/json Content-Length: 65 Connection: close {"id":"1","title":"Hello World!","body":"This is my first post!"} ``` -------------------------------- ### Basic Database Usage Source: https://github.com/silexphp/silex/blob/master/doc/providers/doctrine.rst An example of how to use the 'db' service provided by DoctrineServiceProvider to fetch data from a database. It queries a 'posts' table and displays the title and body of a post. ```php $app->get('/blog/{id}', function ($id) use ($app) { $sql = "SELECT * FROM posts WHERE id = ?"; $post = $app['db']->fetchAssoc($sql, array((int) $id)); return "{$post['body']}
"; }); ``` -------------------------------- ### Define a POST Route for Feedback in Silex Source: https://github.com/silexphp/silex/blob/master/doc/usage.rst Example of defining a POST route to handle feedback submissions, sending an email and returning a response. ```php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; $app->post('/feedback', function (Request $request) { $message = $request->get('message'); mail('feedback@yoursite.com', '[YourSite] Feedback', $message); return new Response('Thank you for your feedback!', 201); }); ``` -------------------------------- ### Configuring Application for Debugging Source: https://github.com/silexphp/silex/blob/master/doc/testing.rst Provides an example of how to enable debug mode and disable the exception handler in createApplication for easier debugging. ```php public function createApplication() { $app = require __DIR__.'/path/to/app.php'; $app['debug'] = true; unset($app['exception_handler']); return $app; } ``` -------------------------------- ### Using Multiple Database Connections Source: https://github.com/silexphp/silex/blob/master/doc/providers/doctrine.rst An example demonstrating how to access and use different database connections when multiple databases are configured. It shows fetching data from 'mysql_read' and updating data in 'mysql_write'. ```php $app->get('/blog/{id}', function ($id) use ($app) { $sql = "SELECT * FROM posts WHERE id = ?"; $post = $app['dbs']['mysql_read']->fetchAssoc($sql, array((int) $id)); $sql = "UPDATE posts SET value = ? WHERE id = ?"; $app['dbs']['mysql_write']->executeUpdate($sql, array('newValue', (int) $id)); return "{$post['body']}
"; }); ``` -------------------------------- ### User Persistence Example Source: https://github.com/silexphp/silex/blob/master/doc/services.rst Demonstrates a PHP class `JsonUserPersister` that takes a base path in its constructor and persists user data to JSON files. This illustrates a basic dependency injection pattern where the base path is provided externally. ```php class JsonUserPersister { private $basePath; public function __construct($basePath) { $this->basePath = $basePath; } public function persist(User $user) { $data = $user->getAttributes(); $json = json_encode($data); $filename = $this->basePath.'/'.$user->id.'.json'; file_put_contents($filename, $json, LOCK_EX); } } ``` -------------------------------- ### Registering a Custom Authentication Provider (WSSE) Source: https://github.com/silexphp/silex/blob/master/doc/providers/security.rst Provides an example of registering a custom authentication provider, WSSE ( a token-based authentication), by defining a service factory. ```php $app['security.authentication_listener.factory.wsse'] = $app->protect(function ($name, $options) use ($app) { // define the authentication provider object $app['security.authentication_provider.'.$name.'.wsse'] = function () use ($app) { return new WsseProvider($app['security.user_provider.default'], __DIR__.'/security_cache'); }; // define the authentication listener object $app['security.authentication_listener.'.$name.'.wsse'] = function () use ($app) { return new WsseListener($app['security.token_storage'], $app['security.authentication_manager']); }; return array( // the authentication provider id 'security.authentication_provider.'.$name.'.wsse', // the authentication listener id 'security.authentication_listener.'.$name.'.wsse', // the entry point id null, // the position of the listener in the stack 'pre_auth' ); }); ``` -------------------------------- ### Sending a File Response Source: https://github.com/silexphp/silex/blob/master/doc/usage.rst Explains how to use the `sendFile` helper method to return files. It covers basic file sending and provides an example of customizing the response using `setContentDisposition` for content type and filename. ```php $app->get('/files/{path}', function ($path) use ($app) { if (!file_exists('/base/path/' . $path)) { $app->abort(404); } return $app->sendFile('/base/path/' . $path); }); ``` ```php return $app ->sendFile('/base/path/' . $path) ->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'pic.jpg') ; ``` -------------------------------- ### Using Container for Dependencies Source: https://github.com/silexphp/silex/blob/master/doc/services.rst An example of how the service container can manage dependencies for a `JsonUserPersister` service, injecting the persistence path as a parameter. ```php $app['user.persist_path'] = '/tmp/users'; $app['user.persister'] = function ($app) { return new JsonUserPersister($app['user.persist_path']); }; ``` -------------------------------- ### Run Development Server Source: https://github.com/silexphp/silex/blob/master/doc/web_servers.rst Starts a local development server for the Silex PHP project. This command is intended for development purposes only and should not be used in production environments. It serves files from the 'web' directory on localhost:8080. ```text $ php -S localhost:8080 -t web web/index.php ``` -------------------------------- ### Adding Validation Dependencies Source: https://github.com/silexphp/silex/blob/master/doc/providers/form.rst Illustrates the Composer commands to install necessary Symfony components (Validator and Config) for enabling form validation features. ```bash composer require symfony/validator symfony/config ``` -------------------------------- ### HTTP Method Routing Source: https://github.com/silexphp/silex/blob/master/doc/usage.rst Defines routes for various HTTP methods like GET, POST, DELETE, and PATCH. Demonstrates basic route definitions. ```php $app->get('/blog/{id}', function ($id) { // ... }); $app->post('/blog', function () { // ... }); $app->delete('/blog/{id}', function ($id) { // ... }); $app->patch('/blog/{id}', function ($id) { // ... }); ``` -------------------------------- ### ESI Support Example Source: https://github.com/silexphp/silex/blob/master/doc/providers/http_cache.rst Illustrates how to use ESI (Edge Side Includes) with Silex by defining included content and setting Surrogate-Control headers. ```php use Symfony\Component\HttpFoundation\Response; $app->get('/', function() { $response = new Response(<<