### 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['title']}

". "

{$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['title']}

". "

{$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['title']}

". "

{$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(<< Hello EOF , 200, array( 'Surrogate-Control' => 'content="ESI/1.0"', )); $response->setTtl(20); return $response; }); $app->get('/included', function() { $response = new Response('Foo'); $response->setTtl(5); return $response; }); $app['http_cache']->run(); ``` -------------------------------- ### Securing a Path with HTTP Basic Authentication Source: https://github.com/silexphp/silex/blob/master/doc/providers/security.rst Provides an example of configuring the security.firewalls to use HTTP basic authentication for a specific URL pattern. ```php $app['security.firewalls'] = array( 'admin' => array( 'pattern' => '^/admin', 'http' => true, 'users' => array( // raw password is foo 'admin' => array('ROLE_ADMIN', '$2y$10$3i9/lVd8UOFIJ6PAMFt8gu3/r5g0qeCJvoSlLCsvMTythye19F77a'), ), ), ); ``` -------------------------------- ### Route Variables Source: https://github.com/silexphp/silex/blob/master/doc/usage.rst Illustrates how to define routes with variable parts and how to match these variables to controller closure arguments. Includes examples with multiple variables and type hinting for Application and Request objects. ```php $app->get('/blog/{id}', function ($id) { // ... }); $app->get('/blog/{postId}/{commentId}', function ($postId, $commentId) { // ... }); $app->get('/blog/{postId}/{commentId}', function ($commentId, $postId) { // ... }); $app->get('/blog/{id}', function (Application $app, Request $request, $id) { // ... }); $app->get('/blog/{id}', function (Application $foo, Request $bar, $id) { // ... }); ``` -------------------------------- ### Testing API Token Authentication with Curl Source: https://github.com/silexphp/silex/blob/master/doc/cookbook/guard_authentication.rst Examples of using curl to test the API token authentication system. Demonstrates requests with no token, a bad token, and a working token. ```bash # test with no token curl http://localhost:8000/ # {"message":"Authentication Required"} # test with a bad token curl -H "X-AUTH-TOKEN: alan" http://localhost:8000/ # {"message":"Username could not be found."} # test with a working token curl -H "X-AUTH-TOKEN: victoria:foo" http://localhost:8000/ # the homepage controller is executed: the page loads normally ``` -------------------------------- ### Basic Form Creation and Handling Source: https://github.com/silexphp/silex/blob/master/doc/providers/form.rst An example of creating a simple form using the `form.factory` service, handling form submissions, and rendering it in a Twig template. It includes basic fields like name, email, and a choice type. ```php use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; $app->match('/form', function (Request $request) use ($app) { // some default data for when the form is displayed the first time $data = array( 'name' => 'Your name', 'email' => 'Your email', ); $form = $app['form.factory']->createBuilder(FormType::class, $data) ->add('name') ->add('email') ->add('billing_plan', ChoiceType::class, array( 'choices' => array('free' => 1, 'small business' => 2, 'corporate' => 3), 'expanded' => true, )) ->add('submit', SubmitType::class, [ 'label' => 'Save', ]) ->getForm(); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); // do something with the data // redirect somewhere return $app->redirect('...'); } // display the form return $app['twig']->render('index.twig', array('form' => $form->createView())); }); ``` -------------------------------- ### Inserting User Data Source: https://github.com/silexphp/silex/blob/master/doc/providers/security.rst Demonstrates how to insert a new user record into the database using Silex's DB layer. This is a basic example of data persistence. ```php $app['db']->insert('users', array( 'username' => 'admin', 'password' => '$2y$10$3i9/lVd8UOFIJ6PAMFt8gu3/r5g0qeCJvoSlLCsvMTythye19F77a', 'roles' => 'ROLE_ADMIN' )); ``` -------------------------------- ### Basic Silex Application Bootstrap Source: https://github.com/silexphp/silex/blob/master/doc/usage.rst Demonstrates the minimal code required to bootstrap a Silex application, including autoloading and running the application. ```php require_once __DIR__.'/../vendor/autoload.php'; $app = new Silex\Application(); // ... definitions $app->run(); ``` -------------------------------- ### Define Controller as a Service and Route Source: https://github.com/silexphp/silex/blob/master/doc/providers/service_controller.rst This example demonstrates defining a controller class ('PostController') as a service and then routing a GET request to a specific action ('indexJsonAction') within that controller. ```php namespace Demo\Controller; use Demo\Repository\PostRepository; use Symfony\Component\HttpFoundation\JsonResponse; class PostController { protected $repo; public function __construct(PostRepository $repo) { $this->repo = $repo; } public function indexJsonAction() { return new JsonResponse($this->repo->findAll()); } } // ... in application setup $app['posts.repository'] = function() { return new PostRepository; }; $app['posts.controller'] = function() use ($app) { return new PostController($app['posts.repository']); }; $app->get('/posts.json', "posts.controller:indexJsonAction"); ``` -------------------------------- ### Manual API Testing with curl Source: https://github.com/silexphp/silex/blob/master/doc/cookbook/json_request_body.rst Command-line example using curl to test the blog post creation API. It sends a POST request with a JSON payload and specifies the Content-Type header. ```bash $ curl http://blog.lo/blog/posts -d '{"title":"Hello World!","body":"This is my first post!"}' -H 'Content-Type: application/json' {"id":"1","title":"Hello World!","body":"This is my first post!"} ``` -------------------------------- ### Define Callable as a Service and Route Source: https://github.com/silexphp/silex/blob/master/doc/providers/service_controller.rst This example shows how to define a plain PHP function as a service and then route a GET request to that service. This offers an alternative to using controller classes. ```php namespace Demo\Controller; use Demo\Repository\PostRepository; use Symfony\Component\HttpFoundation\JsonResponse; function postIndexJson(PostRepository $repo) { return function() use ($repo) { return new JsonResponse($repo->findAll()); }; } // ... in application setup $app['posts.repository'] = function() { return new PostRepository; }; $app['posts.controller'] = function($app) { return Demo\Controller\postIndexJson($app['posts.repository']); }; $app->get('/posts.json', 'posts.controller'); ``` -------------------------------- ### Using HelloServiceProvider Source: https://github.com/silexphp/silex/blob/master/doc/providers.rst Shows how to register and use the HelloServiceProvider within a Silex application. It demonstrates setting a default name and accessing the 'hello' service via a route. ```php use Symfony\Component\HttpFoundation\Request; $app = new Silex\Application(); $app->register(new Acme\HelloServiceProvider(), array( 'hello.default_name' => 'Igor', )); $app->get('/hello', function (Request $request) use ($app) { $name = $request->get('name'); return $app['hello']($name); }); ``` -------------------------------- ### YAML-based Language Files Setup Source: https://github.com/silexphp/silex/blob/master/doc/providers/translation.rst Details the steps to load translations from YAML files, including adding Symfony Config and Yaml components as dependencies, creating YAML locale files, and registering the YamlFileLoader with the translator service. ```bash composer require symfony/config symfony/yaml ``` ```yaml hello: Hello %name% goodbye: Goodbye %name% ``` ```php use Symfony\Component\Translation\Loader\YamlFileLoader; $app->extend('translator', function($translator, $app) { $translator->addLoader('yaml', new YamlFileLoader()); $translator->addResource('yaml', __DIR__.'/locales/en.yml', 'en'); $translator->addResource('yaml', __DIR__.'/locales/de.yml', 'de'); $translator->addResource('yaml', __DIR__.'/locales/fr.yml', 'fr'); return $translator; }); ``` -------------------------------- ### Implementing createApplication Method Source: https://github.com/silexphp/silex/blob/master/doc/testing.rst Details the required createApplication method within a WebTestCase to return the Silex application instance. ```php public function createApplication() { // app.php must return an Application instance return require __DIR__.'/path/to/app.php'; } ``` -------------------------------- ### Silex/Pimple Container Initialization Source: https://github.com/silexphp/silex/blob/master/doc/services.rst Shows how to create a new instance of a Pimple container, which Silex extends. This is the fundamental step for managing services and parameters. ```php $container = new Pimple\Container(); ``` ```php $app = new Silex\Application(); ``` -------------------------------- ### Install Symfony YAML Component Source: https://github.com/silexphp/silex/blob/master/doc/cookbook/validator_yaml.rst Installs the Symfony YAML component using Composer, which is required for loading validation rules from YAML files. ```bash composer require symfony/yaml ``` -------------------------------- ### Registering a Service Provider Source: https://github.com/silexphp/silex/blob/master/doc/providers.rst Demonstrates how to register a custom service provider with the Silex application. It shows the basic registration and how to pass parameters during registration. ```php $app = new Silex\Application(); $app->register(new Acme\DatabaseServiceProvider()); $app->register(new Acme\DatabaseServiceProvider(), array( 'database.dsn' => 'mysql:host=localhost;dbname=myapp', 'database.user' => 'root', 'database.password' => 'secret_root_password', )); ``` -------------------------------- ### PHP Validation Example Source: https://github.com/silexphp/silex/blob/master/doc/providers/validator.rst An example of validating an object in Silex. It creates an Author and Book object, validates them using the validator service, and prints any validation errors or a success message. ```php $app->get('/validate/{email}', function ($email) use ($app) { $author = new Author(); $author->first_name = 'Fabien'; $author->last_name = 'Potencier'; $book = new Book(); $book->title = 'My Book'; $book->author = $author; $errors = $app['validator']->validate($book); if (count($errors) > 0) { foreach ($errors as $error) { echo $error->getPropertyPath().' '.$error->getMessage()."\n"; } } else { echo 'The author is valid'; } }); ``` -------------------------------- ### YAML Validation Rules Example Source: https://github.com/silexphp/silex/blob/master/doc/cookbook/validator_yaml.rst An example of a YAML file (validation.yml) defining validation rules for a 'Post' class. It specifies 'NotNull' and 'NotBlank' constraints for the 'title' property and a minimum length of 100 for the 'body' property. ```yaml # validation.yml Post: properties: title: - NotNull: ~ - NotBlank: ~ body: - Min: 100 ``` -------------------------------- ### Register SerializerServiceProvider Source: https://github.com/silexphp/silex/blob/master/doc/providers/serializer.rst Registers the SerializerServiceProvider with the Silex application. Requires the symfony/serializer component to be installed via composer. ```php $app->register(new Silex\Provider\SerializerServiceProvider()); ``` -------------------------------- ### Lighttpd Configuration Source: https://github.com/silexphp/silex/blob/master/doc/web_servers.rst A sample lighttpd configuration for Silex, defining the document root and URL rewriting rules for routing and static assets. ```lighttpd server.document-root = "/path/to/app" url.rewrite-once = ( # configure some static files "^/assets/.+" => "$0", "^/favicon\.ico$" => "$0", "^(/[^?]*)(?.*)?" => "/index.php$1$2" ) ``` -------------------------------- ### Rendering a Twig Template Source: https://github.com/silexphp/silex/blob/master/doc/providers/twig.rst Example of using the 'twig' service to render a Twig template and pass variables to it. ```php $app->get('/hello/{name}', function ($name) use ($app) { return $app['twig']->render('hello.twig', array( 'name' => $name, )); }); ``` -------------------------------- ### Registering SecurityServiceProvider Source: https://github.com/silexphp/silex/blob/master/doc/providers/security.rst Demonstrates how to register the SecurityServiceProvider with Silex, including the necessary dependency. ```php $app->register(new Silex\Provider\SecurityServiceProvider(), array( 'security.firewalls' => // see below )); ``` -------------------------------- ### Organizing Controllers with Factories and Mounting Source: https://github.com/silexphp/silex/blob/master/doc/organizing_controllers.rst Demonstrates how to group controllers logically using `$app['controllers_factory']` for different sections (blog, forum, admin) and mount them onto the main application. This includes recursive mounting for nested structures. ```php $blog = $app['controllers_factory']; $blog->get('/', function () { return 'Blog home page'; }); $forum = $app['controllers_factory']; $forum->get('/', function () { return 'Forum home page'; }); $app->get('/', function () { return 'Main home page'; }); $app->mount('/blog', $blog); $app->mount('/forum', $forum); $app->mount('/admin', function ($admin) { $admin->mount('/blog', function ($user) { $user->get('/', function () { return 'Admin Blog home page'; }); }); }); ``` -------------------------------- ### URL Generation Shortcuts Source: https://github.com/silexphp/silex/blob/master/doc/services.rst Demonstrates the use of shortcuts provided by the `UrlGeneratorTrait` for generating URL paths and absolute URLs based on route names. ```php $app->path('homepage'); $app->url('homepage'); ``` -------------------------------- ### Validating a Single Value (Email) Source: https://github.com/silexphp/silex/blob/master/doc/providers/validator.rst Example of validating a single value, like an email address, using the validator service. ```php use Symfony\Component\Validator\Constraints as Assert; $app->get('/validate/{email}', function ($email) use ($app) { $errors = $app['validator']->validate($email, new Assert\Email()); if (count($errors) > 0) { return (string) $errors; } else { return 'The email is valid'; } }); ``` -------------------------------- ### Sending Email in a Silex Route Source: https://github.com/silexphp/silex/blob/master/doc/providers/swiftmailer.rst Provides an example of how to send an email using the 'mailer' service within a Silex route handler. ```php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; $app->post('/feedback', function (Request $request) use ($app) { $message = \Swift_Message::newInstance() ->setSubject('[YourSite] Feedback') ->setFrom(array('noreply@yoursite.com')) ->setTo(array('feedback@yoursite.com')) ->setBody($request->get('message')); $app['mailer']->send($message); return new Response('Thank you for your feedback!', 201); }); ``` -------------------------------- ### Basic Route Definition with Assertions Source: https://github.com/silexphp/silex/blob/master/doc/usage.rst Defines a GET route for '/blog/{postId}/{commentId}' and asserts that 'postId' and 'commentId' must be digits. ```php $app->get('/blog/{postId}/{commentId}', function ($postId, $commentId) { // ... }) ->assert('postId', '\d+') ->assert('commentId', '\d+'); ``` -------------------------------- ### HttpFragmentServiceProvider Parameters and Services Source: https://github.com/silexphp/silex/blob/master/doc/providers/http_fragment.rst Details the configurable parameters and available services provided by the HttpFragmentServiceProvider. ```APIDOC HttpFragmentServiceProvider: Parameters: fragment.path: The path for ESI and HInclude URLs ('/_fragment' by default). uri_signer.secret: Secret for the URI signer service (used for HInclude renderer). fragment.renderers.hinclude.global_template: Content or Twig template for default HInclude content. Services: fragment.handler: An instance of Symfony\Component\HttpKernel\Fragment\FragmentHandler. fragment.renderers: An array of fragment renderers (inline, ESI, HInclude by default). ``` -------------------------------- ### Generating URLs in Twig Templates Source: https://github.com/silexphp/silex/blob/master/doc/providers/twig.rst Examples of using the 'path()' and 'url()' Twig functions provided by the Symfony Twig bridge to generate URLs. ```jinja {{ path('homepage') }} {{ url('homepage') }} {# generates the absolute url http://example.org/ #} {{ path('hello', {name: 'Fabien'}) }} {{ url('hello', {name: 'Fabien'}) }} {# generates the absolute url http://example.org/hello/Fabien #} ``` -------------------------------- ### UrlGeneratorTrait Shortcuts Source: https://github.com/silexphp/silex/blob/master/doc/providers/routing.rst Explains the shortcut methods 'path' and 'url' provided by the UrlGeneratorTrait for generating URLs. ```php $app->path('homepage'); $app->url('homepage'); ``` -------------------------------- ### Form Creation with Validation Source: https://github.com/silexphp/silex/blob/master/doc/providers/form.rst An example demonstrating how to add validation constraints (like NotBlank, Length, Email, Choice) to form fields when using the ValidatorServiceProvider. ```php use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Validator\Constraints as Assert; $app->register(new Silex\Provider\ValidatorServiceProvider()); $app->register(new Silex\Provider\TranslationServiceProvider(), array( 'translator.domains' => array(), )); $form = $app['form.factory']->createBuilder(FormType::class) ->add('name', TextType::class, array( 'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))) )) ->add('email', TextType::class, array( 'constraints' => new Assert\Email() )) ->add('billing_plan', ChoiceType::class, array( 'choices' => array('free' => 1, 'small business' => 2, 'corporate' => 3), 'expanded' => true, 'constraints' => new Assert\Choice(array(1, 2, 3)), )) ->add('submit', SubmitType::class, [ 'label' => 'Save', ]) ->getForm(); ``` -------------------------------- ### Using SwiftmailerTrait shortcut Source: https://github.com/silexphp/silex/blob/master/doc/providers/swiftmailer.rst Demonstrates the usage of the 'mail' shortcut provided by the Silex\Application\SwiftmailerTrait for sending emails. ```php $app->mail(\Swift_Message::newInstance() ->setSubject('[YourSite] Feedback') ->setFrom(array('noreply@yoursite.com')) ->setTo(array('feedback@yoursite.com')) ->setBody($request->get('message'))); ``` -------------------------------- ### Adding Twig Bridge Dependency Source: https://github.com/silexphp/silex/blob/master/doc/providers/form.rst Provides the Composer command to install the Symfony Twig Bridge, which is needed for rendering forms within Twig templates. ```bash composer require symfony/twig-bridge ``` -------------------------------- ### Installing Symfony Security CSRF Component Source: https://github.com/silexphp/silex/blob/master/doc/providers/csrf.rst Shows the Composer command to add the Symfony Security CSRF component as a project dependency. ```bash composer require symfony/security-csrf ``` -------------------------------- ### Using the Test Client to Make Requests Source: https://github.com/silexphp/silex/blob/master/doc/testing.rst Shows how to use the client provided by WebTestCase to simulate HTTP requests and interact with the application. ```php public function testInitialPage() { $client = $this->createClient(); $crawler = $client->request('GET', '/'); $this->assertTrue($client->getResponse()->isOk()); $this->assertCount(1, $crawler->filter('h1:contains("Contact us")')); $this->assertCount(1, $crawler->filter('form')); // ... } ``` -------------------------------- ### Match All Methods and Method Restriction Source: https://github.com/silexphp/silex/blob/master/doc/usage.rst Demonstrates using the `match` method to handle any HTTP method and how to restrict it to specific methods using the `method` method. ```php $app->match('/blog', function () { // ... }); $app->match('/blog', function () { // ... }) ->method('PATCH'); $app->match('/blog', function () { // ... }) ->method('PUT|POST'); ``` -------------------------------- ### View Handler with Content Negotiation Source: https://github.com/silexphp/silex/blob/master/doc/usage.rst An example of a view handler that uses the Accept header to negotiate the response format (JSON or XML) using a negotiator service. ```php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; $app->view(function (array $controllerResult, Request $request) use ($app) { $acceptHeader = $request->headers->get('Accept'); $bestFormat = $app['negotiator']->getBestFormat($acceptHeader, array('json', 'xml')); if ('json' === $bestFormat) { return new JsonResponse($controllerResult); } if ('xml' === $bestFormat) { return $app['serializer.xml']->renderResponse($controllerResult); } return $controllerResult; }); ``` -------------------------------- ### Defining Factory Services Source: https://github.com/silexphp/silex/blob/master/doc/services.rst Explains how to create factory services that return a new instance every time they are accessed. This is achieved by wrapping the service definition closure with the `factory()` method. ```php $app['some_service'] = $app->factory(function () { return new Service(); }); ``` -------------------------------- ### Registering HttpFragmentServiceProvider Source: https://github.com/silexphp/silex/blob/master/doc/providers/http_fragment.rst Demonstrates how to register the HttpFragmentServiceProvider in a Silex application. ```php $app->register(new Silex\Provider\HttpFragmentServiceProvider()); ``` -------------------------------- ### Twig Configuration Service Change Source: https://github.com/silexphp/silex/blob/master/doc/changelog.rst Illustrates the removal of the 'twig.configure' service and the recommended use of the 'extend' method for customizing Twig. It provides 'before' and 'after' code examples. ```php $app['twig.configure'] = $app->protect(function ($twig) use ($app) { // do something }); ``` ```php $app['twig'] = $app->share($app->extend('twig', function($twig, $app) { // do something return $twig; })); ``` -------------------------------- ### Using asset() and asset_version() in Twig Source: https://github.com/silexphp/silex/blob/master/doc/providers/asset.rst Examples of how to use the asset() and asset_version() functions within Twig templates for referencing web assets, including named packages. ```jinja {{ asset('/css/foo.png') }} {{ asset('/css/foo.css', 'css') }} {{ asset('/img/foo.png', 'images') }} {{ asset_version('/css/foo.png') }} ``` -------------------------------- ### Registering Multiple Databases Source: https://github.com/silexphp/silex/blob/master/doc/providers/doctrine.rst Shows how to configure the DoctrineServiceProvider to manage multiple database connections. The 'dbs.options' parameter is used, where each key represents a connection name and its value is the connection configuration. ```php $app->register(new Silex\Provider\DoctrineServiceProvider(), array( 'dbs.options' => array ( 'mysql_read' => array( 'driver' => 'pdo_mysql', 'host' => 'mysql_read.someplace.tld', 'dbname' => 'my_database', 'user' => 'my_username', 'password' => 'my_password', 'charset' => 'utf8mb4', ), 'mysql_write' => array( 'driver' => 'pdo_mysql', 'host' => 'mysql_write.someplace.tld', 'dbname' => 'my_database', 'user' => 'my_username', 'password' => 'my_password', 'charset' => 'utf8mb4', ), ), )); ```