Symfony2 fast reference

Click here to load reader

  • date post

  • Category


  • view

  • download


Embed Size (px)


This is my summary of Symfony2 documentation.

Transcript of Symfony2 fast reference

Symfony2 fast reference by Eduardo CobianInstalling and Configuring Symfony The download page is at If you have Git installed on your computer, you should download Symfony2 "without vendors", as it adds a bit more flexibility when including third-party/vendor libraries. if you downloaded the archive "without vendors", install the vendors by running the following command from the command line: php bin/vendors install You can safely ignore the entire vendor/ directory and not commit it to source control. With Git, this is done by creating and adding the following to a .gitignore file: vendor/ Now, the vendor directory won't be committed to source control. To make sure your Web server and PHP are configured to use Symfony use the following URL to check your configuration: http://localhost/Symfony/web/config.php The app/cache and app/logs directories must be writable both by the web server and the command line user. In order to have Code coverage generated xDebug must be installed. To do that modify php/php.ini configuration file with: zend_extension = "C:\xampp\php\ext\php_xdebug.dll" xdebug.remote_enable=on xdebug.remote_host= xdebug.remote_port=9000 xdebug.remote_handler=dbgp A virtual host must be configured in apache/config/extra/httpd-vhosts.conf ServerAdmin [email protected] DirectoryIndex app_dev.php DocumentRoot "C:/xampp/htdocs/" ServerName ServerAlias

Application Configuration By default, the main configuration file es app/config/config.yml imports: - { resource: parameters.ini } - { resource: security.yml } framework: secret: "%secret%" charset: UTF-8 router: { resource: "%kernel.root_dir%/config/routing.yml" }


form: true csrf_protection: true validation: { enable_annotations: true } templating: { engines: ['twig'] } #assets_version: SomeVersionScheme session: default_locale: "%locale%" auto_start: true # Twig Configuration twig: debug: "%kernel.debug%" strict_variables: "%kernel.debug%" Each top-level entry like framework or twig defines the configuration for a particular bundle. I had to change symfony/web/.htaccess: RewriteRule ^(.*)$ app_dev.php [QSA,L] Environments A Symfony2 project generally begins with three environments (dev, test and prod), The dev environment will log warnings and errors, while a prod environment will only log errors. Since the prod environment is optimized for speed; the configuration, routing and Twig templates are compiled into flat PHP classes and cached. When viewing changes in the prod environment, you'll need to clear these cached files and allow them to rebuild: php app/console cache:clear --env=prod --no-debug The test environment is used when running automated tests and cannot be accessed directly through the browser. The requesto object The Request class is a simple object-oriented representation of the HTTP request message use Symfony\Component\HttpFoundation\Request; $request = Request::createFromGlobals(); // or $request = $this->getRequest(); $request->isXmlHttpRequest(); // is it an Ajax request? // retrieve GET and POST variables respectively $request->query->get('foo'); $request->request->get('bar', 'default value'); // retrieve SERVER variables $request->server->get('HTTP_HOST'); // retrieves an instance of UploadedFile identified by foo $request->files->get('foo'); // retrieve a COOKIE value $request->cookies->get('PHPSESSID'); // retrieve an HTTP request header, with normalized, lowercase keys $request->headers->get('host'); $request->headers->get('content_type'); $request->getMethod(); // GET, POST, PUT, DELETE, HEAD $request->getLanguages(); // an array of languages the client accepts The objects query & request are a ParameterBag. Clean the input parameters with the mysql_real_escape_string() function to avoid an injection attack. The Response Object


Symfony also provides a Response class: a simple PHP representation of an HTTP response message use Symfony\Component\HttpFoundation\Response; $response = new Response('Hello '.$name, 200); // or $response = new Response(json_encode(array('name' => $name))); $response->setContent('Hello world!'); $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/html'); // prints the HTTP headers followed by the content $response->send(); The Front Controller A single PHP file handles every request coming into your application. Using Apache's mod_rewrite / index.php/contact will be cleaned up to be just /contact by having this in symfony/web/.htaccess: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ app_dev.php [QSA,L] The front controller web/app_dev.php es el de desarrollo. El de productivo es web/app.php: require_once __DIR__.'/../app/bootstrap.php'; require_once __DIR__.'/../app/AppKernel.php'; use Symfony\Component\HttpFoundation\Request; $kernel = new AppKernel('prod', false); $kernel->handle(Request::createFromGlobals())->send();

Developing with Symfony 1. The Bundle A bundle is nothing more than a directory that houses everything related to a specific feature, including PHP classes, configuration, and even stylesheets and Javascript files To create a bundle called AcmeHelloBundle run the following command and follow the on-screen instructions (use all of the default options): php app/console generate:bundle --namespace=Acme/HelloBundle --format=yml A directory is created for the bundle at src/Acme/HelloBundle. A line is automatically added to the app/AppKernel.php file so that the bundle is registered with the kernel: public function registerBundles() { $bundles = array( // ... new Acme\HelloBundle\AcmeHelloBundle(), render(... is equivalento to: $content = $this->renderView(' . return new Response($content); you can also have Symfony pass you the Request object as an argument to your controller. This is especially convenient when you're working with forms: public function updateAction( Request $request) $form = $this->createForm(...); $form->bindRequest($request); 4. Twig templates Symfony2 comes standard with a templating engine called Twig. Twig templates are meant to be simple and won't process PHP tags. This is by design: the Twig template system is meant to express presentation, not program logic. {# src/Acme/BlogBundle/Resources/views/Default/index.html.twig #}