Commit 3266c735 authored by Fabien Potencier's avatar Fabien Potencier

added application traits for PHP 5.4

parent 199b6ad4
...@@ -15,6 +15,8 @@ Changelog ...@@ -15,6 +15,8 @@ Changelog
// or even better // or even better
$controllers = $app['controllers_factory']; $controllers = $app['controllers_factory'];
* **2012-06-17**: added application traits for PHP 5.4
* **2012-06-16**: renamed ``request.default_locale`` to ``locale`` * **2012-06-16**: renamed ``request.default_locale`` to ``locale``
* **2012-06-16**: Removed the ``translator.loader`` service. See documentation * **2012-06-16**: Removed the ``translator.loader`` service. See documentation
......
...@@ -143,5 +143,16 @@ form by adding constraints on the fields:: ...@@ -143,5 +143,16 @@ form by adding constraints on the fields::
)) ))
->getForm(); ->getForm();
Traits
------
``Silex\Application\FormTrait`` adds the following shortcuts:
* **form**: Creates a FormBuilder instance.
.. code-block:: php
$app->form('form', $data);
For more information, consult the `Symfony2 Forms documentation For more information, consult the `Symfony2 Forms documentation
<http://symfony.com/doc/2.1/book/forms.html>`_. <http://symfony.com/doc/2.1/book/forms.html>`_.
...@@ -72,5 +72,16 @@ add log entries for any logging level through ``addDebug()``, ``addInfo()``, ...@@ -72,5 +72,16 @@ add log entries for any logging level through ``addDebug()``, ``addInfo()``,
return new Response('', 201); return new Response('', 201);
}); });
Traits
------
``Silex\Application\MonologTrait`` adds the following shortcuts:
* **log**: Logs a message.
.. code-block:: php
$app->log(sprintf("User '%s' registered.", $username));
For more information, check out the `Monolog documentation For more information, check out the `Monolog documentation
<https://github.com/Seldaek/monolog>`_. <https://github.com/Seldaek/monolog>`_.
...@@ -466,3 +466,18 @@ sample users:: ...@@ -466,3 +466,18 @@ sample users::
If you are using the Doctrine ORM, the Symfony bridge for Doctrine If you are using the Doctrine ORM, the Symfony bridge for Doctrine
provides a user provider class that is able to load users from your provides a user provider class that is able to load users from your
entities. entities.
Traits
------
``Silex\Application\SecurityTrait`` adds the following shortcuts:
* **user**: Returns the current user.
* **encodePassword**: Encode a given password.
.. code-block:: php
$user = $app->user();
$encoded = $app->encodePassword($user, 'foo');
...@@ -86,5 +86,20 @@ The Swiftmailer provider provides a ``mailer`` service:: ...@@ -86,5 +86,20 @@ The Swiftmailer provider provides a ``mailer`` service::
return new Response('Thank you for your feedback!', 201); return new Response('Thank you for your feedback!', 201);
}); });
Traits
------
``Silex\Application\SwiftmailerTrait`` adds the following shortcuts:
* **mail**: Sends an email.
.. code-block:: php
$app->mail(\Swift_Message::newInstance()
->setSubject('[YourSite] Feedback')
->setFrom(array('noreply@yoursite.com'))
->setTo(array('feedback@yoursite.com'))
->setBody($request->get('message')));
For more information, check out the `Swift Mailer documentation For more information, check out the `Swift Mailer documentation
<http://swiftmailer.org>`_. <http://swiftmailer.org>`_.
...@@ -95,6 +95,22 @@ The above example will result in following routes: ...@@ -95,6 +95,22 @@ The above example will result in following routes:
* ``/it/hello/igor`` will return ``Hello igor`` (because of the fallback). * ``/it/hello/igor`` will return ``Hello igor`` (because of the fallback).
Traits
------
``Silex\Application\TranslationTrait`` adds the following shortcuts:
* **trans**: Translates the given message.
* **transChoice**: Translates the given choice message by choosing a
translation according to a number.
.. code-block:: php
$app->trans('Hello World');
$app->transChoice('Hello World');
Recipes Recipes
------- -------
......
...@@ -120,6 +120,27 @@ from a template: ...@@ -120,6 +120,27 @@ from a template:
{# or if you are also using UrlGeneratorServiceProvider with the SymfonyBridgesServiceProvider #} {# or if you are also using UrlGeneratorServiceProvider with the SymfonyBridgesServiceProvider #}
{{ render(path('sidebar')) }} {{ render(path('sidebar')) }}
Traits
------
``Silex\Application\TwigTrait`` adds the following shortcuts:
* **render**: Renders a view with the given parameters and returns a Response
object.
* **stream**:: Streams a view and returns a Response.
.. code-block:: php
return $app->render('index.html', ['name': 'Fabien']);
return $app->stream('index.html', ['name': 'Fabien']);
$response = new Response();
$response->setTtl(10);
return $app->render('index.html', ['name': 'Fabien'], $response);
Customization Customization
------------- -------------
......
...@@ -61,3 +61,17 @@ Moreover, if you use Twig, you will have access to the ``path()`` and ...@@ -61,3 +61,17 @@ Moreover, if you use Twig, you will have access to the ``path()`` and
{{ path('homepage') }} {{ path('homepage') }}
{{ url('homepage') }} {# generates the absolute url http://example.org/ #} {{ url('homepage') }} {# generates the absolute url http://example.org/ #}
Traits
------
``Silex\Application\UrlGeneratorTrait`` adds the following shortcuts:
* **path**: Generates a path.
* **url**: Generates an absolute URL.
.. code-block:: php
$app->path('homepage');
$app->url('homepage');
...@@ -738,6 +738,34 @@ after every chunk:: ...@@ -738,6 +738,34 @@ after every chunk::
fclose($fh); fclose($fh);
}; };
Traits
------
Silex comes with PHP traits that add some shortcut methods to your Application
class.
.. caution::
You need to use PHP 5.4 or later to benefit from this feature.
Almost all built-in service providers have a corresponding PHP trait. To use
them, define your own application and include the traits you want::
use Silex\Application;
class MyApplication extends Application
{
use Application\TwigTrait;
use Application\SecurityTrait;
use Application\FormTrait;
use Application\UrlGeneratorTrait;
use Application\SwiftmailerTrait;
use Application\MonologTrait;
use Application\TranslationTrait;
}
Read each provider chapter to learn more about the added methods.
Security Security
-------- --------
......
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Silex\Application;
use Symfony\Component\Form\FormBuilder;
/**
* Form trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait FormTrait
{
/**
* Creates and returns a form builder instance
*
* @param mixed $data The initial data for the form
* @param array $options Options for the form
*
* @return FormBuilder
*/
public function form($data = null, array $options = array())
{
return $this['form.factory']->createBuilder('form', $data, $options);
}
}
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Silex\Application;
use Monolog\Logger;
/**
* Monolog trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait MonologTrait
{
/**
* Adds a log record.
*
* @param string $message The log message
* @param array $context The log context
* @param integer $level The logging level
*
* @return Boolean Whether the record has been processed
*/
public function log($message, array $context = array(), $level = Logger::INFO)
{
return $this['monolog']->addRecord($level, $message, $context);
}
}
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Silex\Application;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Security trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait SecurityTrait
{
/**
* Gets a user from the Security Context.
*
* @return mixed
*
* @see TokenInterface::getUser()
*/
public function user()
{
if (null === $token = $this['security']->getToken()) {
return null;
}
if (!is_object($user = $token->getUser())) {
return null;
}
return $user;
}
/**
* Encodes the raw password.
*
* @param UserInterface $user A UserInterface instance
* @param string $raw The password to encode
*
* @return string The encoded password
*
* @throws \RuntimeException when no password encoder could be found for the user
*/
public function encodePassword(UserInterface $user, $password)
{
return $this['security.encoder_factory']->getEncoder($user)->encodePassword($password, $user->getSalt());
}
}
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Silex\Application;
/**
* Swiftmailer trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait SwiftmailerTrait
{
/**
* Sends an email.
*
* @param \Swift_Message $message A \Swift_Message intance
*/
public function mail(\Swift_Message $message)
{
return $this['mailer']->send($message);
}
}
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Silex\Application;
/**
* Translation trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait TranslationTrait
{
/**
* Translates the given message.
*
* @param string $id The message id
* @param array $parameters An array of parameters for the message
* @param string $domain The domain for the message
* @param string $locale The locale
*
* @return string The translated string
*/
public function trans($id, array $parameters = array(), $domain = 'messages', $locale = null)
{
return $app['translator']->trans($id, $parameters, $domain, $locale);
}
/**
* Translates the given choice message by choosing a translation according to a number.
*
* @param string $id The message id
* @param integer $number The number to use to find the indice of the message
* @param array $parameters An array of parameters for the message
* @param string $domain The domain for the message
* @param string $locale The locale
*
* @return string The translated string
*/
public function transChoice($id, $number, array $parameters = array(), $domain = 'messages', $locale = null)
{
return $app['translator']->transChoice($id, $number, $parameters, $domain, $locale);
}
}
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Twig trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait TwigTrait
{
/**
* Renders a view and returns a Response.
*
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
* @param Response $response A Response instance
*
* @return Response A Response instance
*/
public function render($view, array $parameters = array(), Response $response = null)
{
if (null === $response) {
$response = new Response();
}
$response->setContent($this->renderView($view, $parameters));
return $response;
}
/**
* Streams a view.
*
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
* @param StreamedResponse $response A response instance
*
* @return StreamedResponse A StreamedResponse instance
*/
public function stream($view, array $parameters = array(), StreamedResponse $response = null)
{
$twig = $this['twig'];
$callback = function () use ($twig, $view, $parameters) {
$this['twig']->display($view, $parameters);
};
if (null === $response) {
return new StreamedResponse($callback);
}
$response->setCallback($callback);
return $response;
}
/**
* Renders a view.
*
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
*
* @return Response A Response instance
*/
public function renderView($view, array $parameters = array())
{
return $this['twig']->render($view, $parameters);
}
}
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Silex\Application;
/**
* UrlGenerator trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait UrlGeneratorTrait
{
/**
* Generates a path from the given parameters.
*
* @param string $route The name of the route
* @param mixed $parameters An array of parameters
*
* @return string The generated path
*/
public function path($route, $parameters = array())
{
return $this['url_generator']->generate($route, $parameters, false);
}
/**
* Generates an absolute URL from the given parameters.
*
* @param string $route The name of the route
* @param mixed $parameters An array of parameters
*
* @return string The generated URL
*/
public function url($route, $parameters = array())
{
return $this['url_generator']->generate($route, $parameters, true);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment