Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Submit feedback
Sign in
Toggle navigation
S
Silex
Project overview
Project overview
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Commits
Open sidebar
common
Silex
Commits
58c91cdd
Commit
58c91cdd
authored
Apr 16, 2015
by
Fabien Potencier
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
updated docs for 1.3
parent
8ac61be2
Changes
25
Hide whitespace changes
Inline
Side-by-side
Showing
25 changed files
with
154 additions
and
406 deletions
+154
-406
doc/contributing.rst
doc/contributing.rst
+9
-26
doc/cookbook/error_handler.rst
doc/cookbook/error_handler.rst
+8
-17
doc/cookbook/form_no_csrf.rst
doc/cookbook/form_no_csrf.rst
+3
-3
doc/cookbook/multiple_loggers.rst
doc/cookbook/multiple_loggers.rst
+1
-3
doc/cookbook/session_storage.rst
doc/cookbook/session_storage.rst
+4
-5
doc/cookbook/sub_requests.rst
doc/cookbook/sub_requests.rst
+5
-45
doc/cookbook/translating_validation_messages.rst
doc/cookbook/translating_validation_messages.rst
+2
-2
doc/index.rst
doc/index.rst
+0
-1
doc/internals.rst
doc/internals.rst
+8
-9
doc/intro.rst
doc/intro.rst
+11
-22
doc/middlewares.rst
doc/middlewares.rst
+4
-5
doc/phar.rst
doc/phar.rst
+0
-109
doc/providers.rst
doc/providers.rst
+6
-8
doc/providers/doctrine.rst
doc/providers/doctrine.rst
+2
-5
doc/providers/form.rst
doc/providers/form.rst
+2
-2
doc/providers/http_cache.rst
doc/providers/http_cache.rst
+4
-4
doc/providers/http_fragment.rst
doc/providers/http_fragment.rst
+1
-1
doc/providers/security.rst
doc/providers/security.rst
+1
-1
doc/providers/session.rst
doc/providers/session.rst
+1
-1
doc/providers/translation.rst
doc/providers/translation.rst
+2
-2
doc/providers/twig.rst
doc/providers/twig.rst
+7
-7
doc/providers/validator.rst
doc/providers/validator.rst
+1
-1
doc/services.rst
doc/services.rst
+11
-25
doc/testing.rst
doc/testing.rst
+23
-28
doc/usage.rst
doc/usage.rst
+38
-74
No files found.
doc/contributing.rst
View file @
58c91cdd
Contributing
============
We are open to contributions to the Silex code. If you find
a bug or want to contribute a provider, just follow these
steps.
We are open to contributions to the Silex code. If you find a bug or want to
contribute a provider, just follow these steps:
* Fork `the Silex repository <https://github.com/silexphp/Silex>`_
on github.
* Fork `the Silex repository <https://github.com/silexphp/Silex>`_;
* Make your feature addition or bug fix
.
* Make your feature addition or bug fix
;
* Add tests for it
. This is important so we don't break it in a future version unintentionally.
* Add tests for it
;
* Optionally, add some
technical documentation.
* Optionally, add some
documentation;
* `Send a pull request <https://help.github.com/articles/creating-a-pull-request>`_, to the correct `target branch`_.
Bonus points for topic branches.
* `Send a pull request
<https://help.github.com/articles/creating-a-pull-request>`_, to the correct
`target branch`_.
If you have a big change or would like to discuss something,
please join us on the `mailing list
...
...
@@ -26,22 +25,6 @@ please join us on the `mailing list
Any code you contribute must be licensed under the MIT
License.
Target branch
=============
Before you create a pull request for Silex, you need to determine which branch
to submit it to. Read this section carefully first.
Silex has two active branches: `1.0` and `master` (`1.1`).
* **1.0**: Bugfixes and documentation fixes go into the 1.0 branch. 1.0 is
periodically merged into master. The 1.0 branch targets versions 2.1, 2.2 and
2.3 of Symfony2.
* **1.1**: All new features go into the 1.1 branch. Changes cannot break
backward compatibility. The 1.1 branch targets the 2.3 version of Symfony2.
Writing Documentation
=====================
...
...
doc/cookbook/error_handler.rst
View file @
58c91cdd
Converting Errors to Exceptions
===============================
Silex will catch exceptions that are thrown from within a request/response
cycle. It will however *not* catch PHP errors and notices. You can catch them
by converting them to exceptions, this recipe will tell you how.
Why does Silex not do this?
---------------------------
Silex could do this automatically in theory, but there is a reason why it does
not. Silex acts as a library, this means that it does not mess with any global
state. Since error handlers are global in PHP, it is your responsibility as a
user to register them.
Silex catches exceptions that are thrown from within a request/response cycle.
However, it does *not* catch PHP errors and notices. This recipe tells you how
to catch them by converting them to exceptions.
Registering the ErrorHandler
----------------------------
Fortunately, the ``Symfony/Debug`` package has an ``ErrorHandler`` class that
solves this issue. It converts all errors to exceptions, and exceptions can be
caught
by Silex.
The ``Symfony/Debug`` package has an ``ErrorHandler`` class that solves this
problem. It converts all errors to exceptions, and exceptions are then caught
by Silex.
You r
egister it by calling the static ``register`` method::
R
egister it by calling the static ``register`` method::
use Symfony\Component\Debug\ErrorHandler;
ErrorHandler::register();
It is recommended that you do this in your front controller, i.e.
``web/index.php``.
It is recommended that you do this as early as possible.
Handling fatal errors
---------------------
...
...
doc/cookbook/form_no_csrf.rst
View file @
58c91cdd
...
...
@@ -2,13 +2,13 @@ Disabling CSRF Protection on a Form using the FormExtension
===========================================================
The *FormExtension* provides a service for building form in your application
with the Symfony
2
Form component. By default, the *FormExtension* uses the
with the Symfony Form component. By default, the *FormExtension* uses the
CSRF Protection avoiding Cross-site request forgery, a method by which a
malicious user attempts to make your legitimate users unknowingly submit data
that they don't intend to submit.
You can find more details about CSRF Protection and CSRF token in the
`Symfony
2
Book
`Symfony Book
<http://symfony.com/doc/current/book/forms.html#csrf-protection>`_.
In some cases (for example, when embedding a form in an html email) you might
...
...
@@ -30,6 +30,6 @@ Going further
This specific example showed how to change the ``csrf_protection`` in the
``$options`` parameter of the ``createBuilder()`` function. More of them could
be passed through this parameter, it is as simple as using the Symfony
2
be passed through this parameter, it is as simple as using the Symfony
``getDefaultOptions()`` method in your form classes. `See more here
<http://symfony.com/doc/current/book/forms.html#book-form-creating-form-classes>`_.
doc/cookbook/multiple_loggers.rst
View file @
58c91cdd
Using multiple Monolog Loggers
==============================
Having separate instances of
`Monolog`
for different parts of your system is
Having separate instances of
Monolog
for different parts of your system is
often desirable and allows you to configure them independently, allowing for fine
grained control of where your logging goes and in what detail.
...
...
@@ -67,5 +67,3 @@ the container with the channel name, defaulting to the bundled handler.
new StreamHandler(__DIR__.'/../payments.log', Logger::DEBUG),
);
});
doc/cookbook/session_storage.rst
View file @
58c91cdd
...
...
@@ -2,12 +2,11 @@ Using PdoSessionStorage to store Sessions in the Database
=========================================================
By default, the :doc:`SessionServiceProvider </providers/session>` writes
session information in files using Symfony
2
NativeFileSessionStorage. Most
session information in files using Symfony NativeFileSessionStorage. Most
medium to large websites use a database to store sessions instead of files,
because databases are easier to use and scale in a multi-webserver
environment.
because databases are easier to use and scale in a multi-webserver environment.
Symfony
2
's `NativeSessionStorage
Symfony's `NativeSessionStorage
<http://api.symfony.com/master/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.html>`_
has multiple storage handlers and one of them uses PDO to store sessions,
`PdoSessionHandler
...
...
@@ -88,5 +87,5 @@ PdoSessionStorage needs a database table with 3 columns:
* ``session_time``: Time column (INTEGER)
You can find examples of SQL statements to create the session table in the
`Symfony
2
cookbook
`Symfony cookbook
<http://symfony.com/doc/current/cookbook/configuration/pdo_session_storage.html#example-sql-statements>`_
doc/cookbook/sub_requests.rst
View file @
58c91cdd
...
...
@@ -33,7 +33,7 @@ By calling ``handle``, you can make a sub-request manually. Here's an example::
There's some more things that you need to keep in mind though. In most cases
you will want to forward some parts of the current master request to the
sub-request
. That includes: Cookies, server information,
session.
sub-request
like cookies, server information, or the
session.
Here is a more advanced example that forwards said information (``$request``
holds the master request)::
...
...
@@ -122,12 +122,8 @@ constructing a request::
This is something to be aware of when making sub-requests by hand.
Lack of container scopes
------------------------
While the sub-requests available in Silex are quite powerful, they have their
limits. The major limitation/danger that you will run into is the lack of
scopes on the Pimple container.
Services depending on the Request
---------------------------------
The container is a concept that is global to a Silex application, since the
application object **is** the container. Any request that is run against an
...
...
@@ -137,41 +133,5 @@ Any services depending on the ``request`` service will store the first request
that they get (could be master or sub-request), and keep using it, even if
that request is already over.
For example::
use Symfony\Component\HttpFoundation\Request;
class ContentFormatNegotiator
{
private $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function negotiateFormat(array $serverTypes)
{
$clientAcceptType = $this->request->headers->get('Accept');
...
return $format;
}
}
This example looks harmless, but it might blow up. You have no way of knowing
what ``$request->headers->get()`` will return, because ``$request`` could be
either the master request or a sub-request. The answer in this case is to pass
the request as an argument to ``negotiateFormat``. Then you can pass it in
from a location where you have safe access to the current request: a listener
or a controller.
Here are a few general approaches to working around this issue:
* Use ESI with Varnish.
* Do not inject the request, ever. Use listeners instead, as they can access
the request without storing it.
* Inject the Silex Application and fetch the request from it.
Instead of injecting the ``request`` service, you should always inject the
``request_stack`` one instead.
doc/cookbook/translating_validation_messages.rst
View file @
58c91cdd
Translating Validation Messages
===============================
When working with Symfony
2
validator, a common task would be to show localized
When working with Symfony validator, a common task would be to show localized
validation messages.
In order to do that, you will need to register translator and point to
...
...
@@ -17,4 +17,4 @@ translated resources::
$app['translator']->addResource('xlf', __DIR__.'/vendor/symfony/validator/Symfony/Component/Validator/Resources/translations/validators/validators.sr_Latn.xlf', 'sr_Latn', 'validators');
});
And that's all you need to load translations from Symfony
2
``xlf`` files.
And that's all you need to load translations from Symfony ``xlf`` files.
doc/index.rst
View file @
58c91cdd
...
...
@@ -17,4 +17,3 @@ Silex
providers/index
web_servers
changelog
phar
doc/internals.rst
View file @
58c91cdd
Internals
=========
This chapter will tell you a bit about how Silex works
internally.
This chapter will tell you how Silex works internally.
Silex
-----
...
...
@@ -10,7 +9,7 @@ Silex
Application
~~~~~~~~~~~
The application is the main interface to Silex. It implements Symfony
2
's
The application is the main interface to Silex. It implements Symfony's
`HttpKernelInterface
<http://api.symfony.com/master/Symfony/Component/HttpKernel/HttpKernelInterface.html>`_,
so you can pass a `Request
...
...
@@ -23,8 +22,8 @@ outside as well as the inside. You could replace any service, and you are also
able to read them.
The application makes strong use of the `EventDispatcher
<http://api.symfony.com/master/Symfony/Component/EventDispatcher/EventDispatcher
.html>`_
to hook into the Symfony2
`HttpKernel
<http://api.symfony.com/master/Symfony/Component/EventDispatcher/EventDispatcher
.html>`_ to hook into the Symfony
`HttpKernel
<http://api.symfony.com/master/Symfony/Component/HttpKernel/HttpKernel.html>`_
events. This allows fetching the ``Request``, converting string responses into
``Response`` objects and handling Exceptions. We also use it to dispatch some
...
...
@@ -33,7 +32,7 @@ custom events like before/after middlewares and errors.
Controller
~~~~~~~~~~
The Symfony
2
`Route
The Symfony `Route
<http://api.symfony.com/master/Symfony/Component/Routing/Route.html>`_ is
actually quite powerful. Routes can be named, which allows for URL generation.
They can also have requirements for the variable parts. In order to allow
...
...
@@ -69,10 +68,10 @@ The ``Application`` provides a shortcut ``flush`` method for flushing the
Instead of creating an instance of ``RouteCollection`` yourself, use the
``$app['controllers_factory']`` factory instead.
Symfony
2
-------
-
Symfony
-------
Following Symfony
2
components are used by Silex:
Following Symfony components are used by Silex:
* **HttpFoundation**: For ``Request`` and ``Response``.
...
...
doc/intro.rst
View file @
58c91cdd
Introduction
============
Silex is a PHP microframework
for PHP 5.3. It is built on the shoulders of
`
Symfony2`_ and `
Pimple`_ and also inspired by `Sinatra`_.
Silex is a PHP microframework
. It is built on the shoulders of `Symfony`_ and
`Pimple`_ and also inspired by `Sinatra`_.
A microframework provides the guts for building simple single-file apps. Silex
aims to be:
Silex aims to be:
* *Concise*: Silex exposes an intuitive and concise API
that is fun to use
.
* *Concise*: Silex exposes an intuitive and concise API.
* *Extensible*: Silex has an extension system based around the Pimple
micro
service-container that makes it e
ven easier
to tie in third party libraries.
* *Extensible*: Silex has an extension system based around the Pimple
service-container that makes it e
asy
to tie in third party libraries.
* *Testable*: Silex uses Symfony
2
's HttpKernel which abstracts request and
* *Testable*: Silex uses Symfony's HttpKernel which abstracts request and
response. This makes it very easy to test apps and the framework itself. It
also respects the HTTP specification and encourages its proper use.
...
...
@@ -39,23 +38,13 @@ Usage
All that is needed to get access to the Framework is to include the
autoloader.
Next
a route for ``/hello/{name}`` that matches for ``GET`` requests is defined.
When the route matches, the function is executed and the return value is sent
back to the client.
Next
, a route for ``/hello/{name}`` that matches for ``GET`` requests is
defined. When the route matches, the function is executed and the return value
is sent
back to the client.
Finally, the app is run. Visit ``/hello/world`` to see the result. It's really
that easy!
Installation
------------
Installing Silex is as easy as it can get. The recommend method is using
Composer_ and requiring `silex/silex`_. Another way is to `download`_ the
archive file and extract it.
.. _Symfony2: http://symfony.com/
.. _Symfony: http://symfony.com/
.. _Pimple: http://pimple.sensiolabs.org/
.. _Sinatra: http://www.sinatrarb.com/
.. _Composer: http://getcomposer.org/
.. _`download`: http://silex.sensiolabs.org/download
.. _`silex/silex`: https://packagist.org/packages/silex/silex
doc/middlewares.rst
View file @
58c91cdd
...
...
@@ -34,9 +34,8 @@ early event::
// ...
}, Application::EARLY_EVENT);
Of course, in this case, the routing and the security won't have been
executed, and so you won't have access to the locale, the current route, or
the security user.
In this case, the routing and the security won't have been executed, and so you
won't have access to the locale, the current route, or the security user.
.. note::
...
...
@@ -159,5 +158,5 @@ callback), and the Response is passed to the after middlewares right away::
.. note::
If a before middleware does not return a Response or ``null``,
a
``RuntimeException`` is thrown
.
A ``RuntimeException`` is thrown if a before middleware does not return
a
Response or ``null``
.
doc/phar.rst
deleted
100644 → 0
View file @
8ac61be2
Phar File
=========
.. caution::
Using the Silex ``phar`` file is deprecated. You should use Composer
instead to install Silex and its dependencies or download one of the
archives.
Installing
----------
Installing Silex is as easy as downloading the `phar
<http://silex.sensiolabs.org/get/silex.phar>`_ and storing it somewhere on
the disk. Then, require it in your script::
<?php
require_once 'phar://'.__DIR__.'/silex.phar';
$app = new Silex\Application();
$app->get('/hello/{name}', function ($name) use ($app) {
return 'Hello '.$app->escape($name);
});
$app->run();
Console
-------
Silex includes a lightweight console for updating to the latest version.
To find out which version of Silex you are using, invoke ``silex.phar`` on the
command-line with ``version`` as an argument:
.. code-block:: text
$ php silex.phar version
Silex version 0a243d3 2011-04-17 14:49:31 +0200
To check that your are using the latest version, run the ``check`` command:
.. code-block:: text
$ php silex.phar check
To update ``silex.phar`` to the latest version, invoke the ``update``
command:
.. code-block:: text
$ php silex.phar update
This will automatically download a new ``silex.phar`` from
``silex.sensiolabs.org`` and replace the existing one.
Pitfalls
--------
There are some things that can go wrong. Here we will try and outline the
most frequent ones.
PHP configuration
~~~~~~~~~~~~~~~~~
Certain PHP distributions have restrictive default Phar settings. Setting
the following may help.
.. code-block:: ini
detect_unicode = Off
phar.readonly = Off
phar.require_hash = Off
If you are on Suhosin you will also have to set this:
.. code-block:: ini
suhosin.executor.include.whitelist = phar
.. note::
Ubuntu's PHP ships with Suhosin, so if you are using Ubuntu, you will need
this change.
Phar-Stub bug
~~~~~~~~~~~~~
Some PHP installations have a bug that throws a ``PharException`` when trying
to include the Phar. It will also tell you that ``Silex\Application`` could not
be found. A workaround is using the following include line::
require_once 'phar://'.__DIR__.'/silex.phar/autoload.php';
The exact cause of this issue could not be determined yet.
ioncube loader bug
~~~~~~~~~~~~~~~~~~
Ioncube loader is an extension that can decode PHP encoded file.
Unfortunately, old versions (prior to version 4.0.9) are not working well
with phar archives.
You must either upgrade Ioncube loader to version 4.0.9 or newer or disable it
by commenting or removing this line in your php.ini file:
.. code-block:: ini
zend_extension = /usr/lib/php5/20090626+lfs/ioncube_loader_lin_5.3.so
doc/providers.rst
View file @
58c91cdd
...
...
@@ -32,7 +32,7 @@ Conventions
~~~~~~~~~~~
You need to watch out in what order you do certain things when interacting
with providers. Just keep t
o these rules
:
with providers. Just keep t
hese rules in mind
:
* Overriding existing services must occur **after** the provider is
registered.
...
...
@@ -45,8 +45,6 @@ with providers. Just keep to these rules:
*Reason: Providers can set default values for parameters. Just like with
services, the provider will overwrite existing values.*
Make sure to stick to this behavior when creating your own providers.
Included providers
~~~~~~~~~~~~~~~~~~
...
...
@@ -89,10 +87,10 @@ Providers must implement the ``Silex\ServiceProviderInterface``::
public function boot(Application $app);
}
Th
is is very straight forward, just create a new class that implements the two
m
ethods. In the ``register()`` method, you can define services on the
application which then may make use of other services and parameters. In the
``boot()`` method, you can configure
the application, just before it handles a
Th
e ``register()`` method defines services on the application which then may
m
ake use of other services and parameters.
The ``boot()`` method configures
the application, just before it handles a
request.
Here is an example of such a provider::
...
...
@@ -198,7 +196,7 @@ defined (like ``get``, ``post``, ``match``, ...).
The ``Application`` class acts in fact as a proxy for these methods.
You can
now
use this provider as follows::
You can use this provider as follows::
$app = new Silex\Application();
...
...
doc/providers/doctrine.rst
View file @
58c91cdd
...
...
@@ -2,11 +2,8 @@ DoctrineServiceProvider
=======================
The *DoctrineServiceProvider* provides integration with the `Doctrine DBAL
<http://www.doctrine-project.org/projects/dbal>`_ for easy database access.
.. note::
There is only a Doctrine DBAL. An ORM service is **not** supplied.
<http://www.doctrine-project.org/projects/dbal>`_ for easy database access
(Doctrine ORM integration is **not** supplied).
Parameters
----------
...
...
doc/providers/form.rst
View file @
58c91cdd
...
...
@@ -2,7 +2,7 @@ FormServiceProvider
===================
The *FormServiceProvider* provides a service for building forms in
your application with the Symfony
2
Form component.
your application with the Symfony Form component.
Parameters
----------
...
...
@@ -190,5 +190,5 @@ Traits
$app->form($data);
For more information, consult the `Symfony
2
Forms documentation
For more information, consult the `Symfony Forms documentation
<http://symfony.com/doc/2.3/book/forms.html>`_.
doc/providers/http_cache.rst
View file @
58c91cdd
HttpCacheServiceProvider
========================
The *HttpCacheServiceProvider* provides support for the Symfony
2
Reverse
The *HttpCacheServiceProvider* provides support for the Symfony Reverse
Proxy.
Parameters
...
...
@@ -67,8 +67,8 @@ setting Response HTTP cache headers::
Request::setTrustedProxies(array('127.0.0.1', '::1'));
$app->run();
This provider allows you to use the Symfony
2
reverse proxy natively with
Silex applications by using the ``http_cache`` service. The Symfony
2
reverse proxy
This provider allows you to use the Symfony reverse proxy natively with
Silex applications by using the ``http_cache`` service. The Symfony reverse proxy
acts much like any other proxy would, so you will want to whitelist it:
.. code-block:: php
...
...
@@ -128,5 +128,5 @@ overall performance::
Finally, check that your Web server does not override your caching strategy.
For more information, consult the `Symfony
2
HTTP Cache documentation
For more information, consult the `Symfony HTTP Cache documentation
<http:
//
symfony
.
com
/
doc
/
current
/
book
/
http_cache
.
html
>
`_.
doc/providers/http_fragment.rst
View file @
58c91cdd
HttpFragmentServiceProvider
===========================
The *HttpFragmentServiceProvider* provides support for the Symfony
2
fragment
The *HttpFragmentServiceProvider* provides support for the Symfony fragment
sub-framework, which allows you to embed fragments of HTML in a template.
.. warning::
...
...
doc/providers/security.rst
View file @
58c91cdd
...
...
@@ -83,7 +83,7 @@ Usage
-----
The Symfony Security component is powerful. To learn more about it, read the
`Symfony
2
Security documentation
`Symfony Security documentation
<http://symfony.com/doc/2.3/book/security.html>`_.
.. tip::
...
...
doc/providers/session.rst
View file @
58c91cdd
...
...
@@ -38,7 +38,7 @@ Parameters
Services
--------
* **session**: An instance of Symfony
2
's `Session
* **session**: An instance of Symfony's `Session
<http://api.symfony.com/master/Symfony/Component/HttpFoundation/Session/Session.html>`_.
* **session.storage**: A service that is used for persistence of the session
...
...
doc/providers/translation.rst
View file @
58c91cdd
...
...
@@ -118,7 +118,7 @@ YAML-based language files
Having your translations in PHP files can be inconvenient. This recipe will
show you how to load translations from external YAML files.
First, add the Symfony
2
``Config`` and ``Yaml`` components as dependencies:
First, add the Symfony ``Config`` and ``Yaml`` components as dependencies:
.. code-block:: bash
...
...
@@ -151,7 +151,7 @@ XLIFF-based language files
~~~~~~~~~~~~~~~~~~~~~~~~~~
Just as you would do with YAML translation files, you first need to add the
Symfony
2
``Config`` component as a dependency (see above for details).
Symfony ``Config`` component as a dependency (see above for details).
Then, similarly, create XLIFF files in your locales directory and add them to
the translator::
...
...
doc/providers/twig.rst
View file @
58c91cdd
...
...
@@ -48,11 +48,11 @@ Registering
composer require twig/twig
Symfony
2
Components Integration
------------------------------
-
Symfony Components Integration
------------------------------
Symfony provides a Twig bridge that provides additional integration between
some Symfony
2
components and Twig. Add it as a dependency:
some Symfony components and Twig. Add it as a dependency:
.. code-block:: bash
...
...
@@ -63,24 +63,24 @@ additional capabilities:
* **UrlGeneratorServiceProvider**: If you are using the
``UrlGeneratorServiceProvider``, you will have access to the ``path()`` and
``url()`` functions. You can find more information in the `Symfony
2
Routing
``url()`` functions. You can find more information in the `Symfony Routing
documentation
<http://symfony.com/doc/current/book/routing.html#generating-urls-from-a-template>`_.
* **TranslationServiceProvider**: If you are using the
``TranslationServiceProvider``, you will get the ``trans()`` and
``transchoice()`` functions for translation in Twig templates. You can find
more information in the `Symfony
2
Translation documentation
more information in the `Symfony Translation documentation
<http://symfony.com/doc/current/book/translation.html#twig-templates>`_.
* **FormServiceProvider**: If you are using the ``FormServiceProvider``, you
will get a set of helpers for working with forms in templates. You can find
more information in the `Symfony
2
Forms reference
more information in the `Symfony Forms reference
<http://symfony.com/doc/current/reference/forms/twig_reference.html>`_.
* **SecurityServiceProvider**: If you are using the
``SecurityServiceProvider``, you will have access to the ``is_granted()``
function in templates. You can find more information in the `Symfony
2
function in templates. You can find more information in the `Symfony
Security documentation
<http://symfony.com/doc/current/book/security.html#access-control-in-templates>`_.
...
...
doc/providers/validator.rst
View file @
58c91cdd
...
...
@@ -217,5 +217,5 @@ provider and register the messages under the ``validators`` domain::
),
);
For more information, consult the `Symfony
2
Validation documentation
For more information, consult the `Symfony Validation documentation
<http://symfony.com/doc/master/book/validation.html>`_.
doc/services.rst
View file @
58c91cdd
Services
========
Silex is not only a
microframework. It is also a micro service container. It
does this by extending `Pimple <http://pimple.sensiolabs.org>`_ which provides
service
goodness in just 44 NCLOC.
Silex is not only a
framework, it is also a service container. It does this by
extending `Pimple <http://pimple.sensiolabs.org>`_ which provides service
goodness in just 44 NCLOC.
Dependency Injection
--------------------
...
...
@@ -43,24 +43,14 @@ passed to the constructor. This means you can create several independent
instances with different base paths. Of course dependencies do not have to be
simple strings. More often they are in fact other services.
Container
~~~~~~~~~
A DIC or service container is responsible for creating and storing services.
It can recursively create dependencies of the requested services and inject
them. It does so lazily, which means a service is only created when you
actually need it.
Most containers are quite complex and are configured through XML or YAML
files.
Pimple is different.
A service container is responsible for creating and storing services. It can
recursively create dependencies of the requested services and inject them. It
does so lazily, which means a service is only created when you actually need it.
Pimple
------
Pimple is probably the simplest service container out there. It makes strong
use of closures and implements the ArrayAccess interface.
Pimple makes strong use of closures and implements the ArrayAccess interface.
We will start off by creating a new instance of Pimple -- and because
``Silex\Application`` extends ``Pimple`` all of this applies to Silex as
...
...
@@ -179,8 +169,7 @@ Note that protected closures do not get access to the container.
Core services
-------------
Silex defines a range of services which can be used or replaced. You probably
don't want to mess with most of them.
Silex defines a range of services.
* **request**: Contains the current request object, which is an instance of
`Request
...
...
@@ -191,7 +180,7 @@ don't want to mess with most of them.
$id = $app['request']->get('id');
This is only available when a request is being served
,
you can only access
This is only available when a request is being served
;
you can only access
it from within a controller, an application before/after middlewares, or an
error handler.
...
...
@@ -204,7 +193,7 @@ don't want to mess with most of them.
* **dispatcher**: The `EventDispatcher
<http://api.symfony.com/master/Symfony/Component/EventDispatcher/EventDispatcher.html>`_
that is used internally. It is the core of the Symfony
2
system and is used
that is used internally. It is the core of the Symfony system and is used
quite a bit by Silex.
* **resolver**: The `ControllerResolver
...
...
@@ -214,7 +203,7 @@ don't want to mess with most of them.
* **kernel**: The `HttpKernel
<http://api.symfony.com/master/Symfony/Component/HttpKernel/HttpKernel.html>`_
that is used internally. The HttpKernel is the heart of Symfony
2
, it takes a
that is used internally. The HttpKernel is the heart of Symfony, it takes a
Request as input and returns a Response as output.
* **request_context**: The request context is a simplified representation of
...
...
@@ -230,9 +219,6 @@ don't want to mess with most of them.
the ``MonologServiceProvider`` or define your own ``logger`` service that
conforms to the PSR logger interface.
In versions of Silex before 1.1 this must be a
``Symfony\Component\HttpKernel\Log\LoggerInterface``.
.. note::
All of these Silex core services are shared.
...
...
doc/testing.rst
View file @
58c91cdd
Testing
=======
Because Silex is built on top of Symfony
2
, it is very easy to write functional
Because Silex is built on top of Symfony, it is very easy to write functional
tests for your application. Functional tests are automated software tests that
ensure that your code is working correctly. They go through the user
interface,
using a fake browser, and mimic the actions a user would do.
ensure that your code is working correctly. They go through the user
interface,
using a fake browser, and mimic the actions a user would do.
Why
---
If you are not familiar with software tests, you may be wondering why you
would need this. Every time you make a change to your application, you have to
test
it. This means going through all the pages and making sure they are still
If you are not familiar with software tests, you may be wondering why you
would
need this. Every time you make a change to your application, you have to test
it. This means going through all the pages and making sure they are still
working. Functional tests save you a lot of time, because they enable you to
test your application in usually under a second by running a single command.
For more information on functional testing, unit testing, and automated
software tests in general, check out `PHPUnit
<https://github.com/sebastianbergmann/phpunit>`_ and `Bulat Shakirzyanov's
talk on Clean Code
<http://www.slideshare.net/avalanche123/clean-code-5609451>`_.
<https://github.com/sebastianbergmann/phpunit>`_ and `Bulat Shakirzyanov's talk
on Clean Code <http://www.slideshare.net/avalanche123/clean-code-5609451>`_.
PHPUnit
-------
`PHPUnit <https://github.com/sebastianbergmann/phpunit>`_ is the de-facto
standard testing framework for PHP. It was built for writing unit tests, but
it can be used for functional tests too. You write tests by creating a new
class, that extends the ``PHPUnit_Framework_TestCase``. Your test cases are
methods
prefixed with ``test``::
standard testing framework for PHP. It was built for writing unit tests, but
it
can be used for functional tests too. You write tests by creating a new class,
that extends the ``PHPUnit_Framework_TestCase``. Your test cases are methods
prefixed with ``test``::
class ContactFormTest extends \PHPUnit_Framework_TestCase
{
...
...
@@ -60,7 +59,7 @@ section of the PHPUnit documentation.
WebTestCase
-----------
Symfony
2
provides a WebTestCase class that can be used to write functional
Symfony provides a WebTestCase class that can be used to write functional
tests. The Silex version of this class is ``Silex\WebTestCase``, and you can
use it by making your test extend it::
...
...
@@ -73,7 +72,7 @@ use it by making your test extend it::
.. note::
If you want to use the Symfony
2
``WebTestCase`` class you will need to
If you want to use the Symfony ``WebTestCase`` class you will need to
explicitly install its dependencies for your project:
.. code-block:: bash
...
...
@@ -93,8 +92,8 @@ executed before every test.
.. tip::
By default, the application behaves in the same way as when using it from
a
browser. But when an error occurs, it is sometimes easier to get raw
By default, the application behaves in the same way as when using it from
a
browser. But when an error occurs, it is sometimes easier to get raw
exceptions instead of HTML pages. It is rather simple if you tweak the
application configuration in the ``createApplication()`` method like
follows::
...
...
@@ -122,9 +121,8 @@ executed before every test.
// ...
}
The WebTestCase provides a ``createClient`` method. A client acts as a
browser, and allows you to interact with your application. Here's how it
works::
The WebTestCase provides a ``createClient`` method. A client acts as a browser,
and allows you to interact with your application. Here's how it works::
public function testInitialPage()
{
...
...
@@ -143,7 +141,7 @@ There are several things going on here. You have both a ``Client`` and a
You can also access the application through ``$this->app``.
Client
------
~~~~~~
The client represents a browser. It holds your browsing history, cookies and
more. The ``request`` method allows you to make a request to a page on your
...
...
@@ -152,11 +150,11 @@ application.
.. note::
You can find some documentation for it in `the client section of the
testing chapter of the Symfony
2
documentation
testing chapter of the Symfony documentation
<http://symfony.com/doc/current/book/testing.html#the-test-client>`_.
Crawler
-------
~~~~~~~
The crawler allows you to inspect the content of a page. You can filter it
using CSS expressions and lots more.
...
...
@@ -164,7 +162,7 @@ using CSS expressions and lots more.
.. note::
You can find some documentation for it in `the crawler section of the testing
chapter of the Symfony
2
documentation
chapter of the Symfony documentation
<http://symfony.com/doc/current/book/testing.html#the-test-client>`_.
Configuration
...
...
@@ -195,9 +193,6 @@ look like this:
</testsuites>
</phpunit>
You can also configure a bootstrap file for autoloading and whitelisting for
code coverage reports.
Your ``tests/YourApp/Tests/YourTest.php`` should look like this::
namespace YourApp\Tests;
...
...
@@ -217,4 +212,4 @@ Your ``tests/YourApp/Tests/YourTest.php`` should look like this::
}
}
Now, when running ``phpunit`` on the command line,
your
tests should run.
Now, when running ``phpunit`` on the command line, tests should run.
doc/usage.rst
View file @
58c91cdd
Usage
=====
This chapter describes how to use Silex.
Installation
------------
...
...
@@ -65,17 +63,14 @@ Routing
-------
In Silex you define a route and the controller that is called when that
route is matched.
A route pattern consists of:
route is matched. A route pattern consists of:
* *Pattern*: The route pattern defines a path that points to a resource. The
pattern can include variable parts and you are able to set RegExp
requirements for them.
* *Method*: One of the following HTTP methods: ``GET``, ``POST``, ``PUT`` or
``DELETE``. This describes the interaction with the resource. Commonly only
``GET`` and ``POST`` are used, but it is possible to use the others as well.
``DELETE``. This describes the interaction with the resource.
The controller is defined using a closure like this::
...
...
@@ -83,17 +78,6 @@ The controller is defined using a closure like this::
// ... do something
}
Closures are anonymous functions that may import state from outside of their
definition. This is different from globals, because the outer state does not
have to be global. For instance, you could define a closure in a function and
import local variables of that function.
.. note::
Closures that do not import scope are referred to as lambdas. Because all
anonymous functions are instances of the ``Closure`` class in PHP, the
documentation will not make a distinction here.
The return value of the closure becomes the content of the page.
Example GET Route
...
...
@@ -122,8 +106,8 @@ Here is an example definition of a ``GET`` route::
Visiting ``/blog`` will return a list of blog post titles. The ``use``
statement means something different in this context. It tells the closure to
import the ``$blogPosts`` variable from the outer scope. This allows you to
use
it from within the closure.
import the ``$blogPosts`` variable from the outer scope. This allows you to
use
it from within the closure.
Dynamic Routing
~~~~~~~~~~~~~~~
...
...
@@ -185,7 +169,7 @@ This allows setting an HTTP status code, in this case it is set to
.. note::
Silex always uses a ``Response`` internally, it converts strings to
responses with status code ``200
Ok
``.
responses with status code ``200``.
Other methods
~~~~~~~~~~~~~
...
...
@@ -215,8 +199,7 @@ methods on your application: ``get``, ``post``, ``put``, ``delete``::
<input type="hidden" id="_method" name="_method" value="PUT" />
</form>
If you are using Symfony Components 2.2+, you will need to explicitly
enable this method override::
you need to explicitly enable this method override::
use Symfony\Component\HttpFoundation\Request;
...
...
@@ -355,10 +338,6 @@ convert method will be used as converter::
// ...
})->convert('user', 'converter.user:convert');
.. warning::
Please note that the ability to use a service method (with the `a:b` notation) will be in version 1.2
Requirements
~~~~~~~~~~~~
...
...
@@ -399,10 +378,9 @@ have the value ``index``.
Named Routes
~~~~~~~~~~~~
Some providers (such as ``UrlGeneratorProvider``) can make use of named
routes. By default Silex will generate a route name for you, that cannot
really be used. You can give a route a name by calling ``bind`` on the
``Controller`` object that is returned by the routing methods::
Some providers (such as ``UrlGeneratorProvider``) can make use of named routes.
By default Silex will generate an internal route name for you but you can give
an explicit route name by calling ``bind``::
$app->get('/', function () {
// ...
...
...
@@ -414,17 +392,12 @@ really be used. You can give a route a name by calling ``bind`` on the
})
->bind('blog_post');
.. note::
It only makes sense to name routes if you use providers that make use of
the ``RouteCollection``.
Controllers in Classes
Controllers as Classes
~~~~~~~~~~~~~~~~~~~~~~
I
f you don't want to use anonymous functions, you can also define your
controllers as methods. By using the ``ControllerClass::methodName`` syntax,
you can tell
Silex to lazily create the controller object for you::
I
nstead of anonymous functions, you can also define your controllers as
methods. By using the ``ControllerClass::methodName`` syntax, you can tell
Silex to lazily create the controller object for you::
$app->get('/', 'Acme\\Foo::bar');
...
...
@@ -446,14 +419,14 @@ This will load the ``Acme\Foo`` class on demand, create an instance and call
the ``bar`` method to get the response. You can use ``Request`` and
``Silex\Application`` type hints to get ``$request`` and ``$app`` injected.
For an even stronger separation between Silex and your controllers, you can
:doc:`define your controllers as services
<providers/service_controller>`.
It is also possible to :doc:`define your controllers as services
<providers/service_controller>`.
Global Configuration
--------------------
If a controller setting must be applied to
all
controllers (a converter, a
middleware, a requirement, or a default value),
you can
configure it on
If a controller setting must be applied to
**all**
controllers (a converter, a
middleware, a requirement, or a default value), configure it on
``$app['controllers']``, which holds all application controllers::
$app['controllers']
...
...
@@ -474,16 +447,12 @@ the defaults for new controllers.
mount as they have their own global configuration (read the
:doc:`dedicated chapter<organizing_controllers>` for more information).
.. warning::
The converters are run for **all** registered controllers.
Error Handlers
--------------
If some part of your code throws an exception you will want to display some
kind of error page to the user. This is what error handlers do. You can also
use them to do additional things, such as
logging.
When an exception is thrown, error handlers allows you to display a custom
error page to the user. They can also be used to do additional things, such as
logging.
To register an error handler, pass a closure to the ``error`` method which
takes an ``Exception`` argument and returns a response::
...
...
@@ -511,15 +480,6 @@ handle them differently::
return new Response($message);
});
.. note::
As Silex ensures that the Response status code is set to the most
appropriate one depending on the exception, setting the status on the
response won't work. If you want to overwrite the status code (which you
should not without a good reason), set the ``X-Status-Code`` header::
return new Response('Error', 404 /* ignored */, array('X-Status-Code' => 200));
You can restrict an error handler to only handle some Exception classes by
setting a more specific type hint for the Closure argument::
...
...
@@ -528,9 +488,18 @@ setting a more specific type hint for the Closure argument::
// and exceptions that extends \LogicException
});
If you want to set up logging you can use a separate error handler for that.
Just make sure you register it before the response error handlers, because
once a response is returned, the following handlers are ignored.
.. note::
As Silex ensures that the Response status code is set to the most
appropriate one depending on the exception, setting the status on the
response won't work. If you want to overwrite the status code, set the
``X-Status-Code`` header::
return new Response('Error', 404 /* ignored */, array('X-Status-Code' => 200));
If you want to use a separate error handler for logging, make sure you register
it before the response error handlers, because once a response is returned, the
following handlers are ignored.
.. note::
...
...
@@ -627,8 +596,8 @@ response for you::
Streaming
---------
It's possible to
create a streaming response, which is important in cases when
you cannot
buffer the data being sent::
It's possible to
stream a response, which is important in cases when you don't
want to
buffer the data being sent::
$app->get('/images/{file}', function ($file) use ($app) {
if (!file_exists(__DIR__.'/images/'.$file)) {
...
...
@@ -661,7 +630,7 @@ Sending a file
If you want to return a file, you can use the ``sendFile`` helper method.
It eases returning files that would otherwise not be publicly available. Simply
pass it your file path, status code, headers and the content disposition and it
will create a ``BinaryFileResponse``
based
response for you::
will create a ``BinaryFileResponse`` response for you::
$app->get('/files/{path}', function ($path) use ($app) {
if (!file_exists('/base/path/' . $path)) {
...
...
@@ -680,10 +649,6 @@ To further customize the response before returning it, check the API doc for
->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'pic.jpg')
;
.. note::
HttpFoundation 2.2 or greater is required for this feature to be available.
Traits
------
...
...
@@ -733,9 +698,8 @@ Make sure to protect your application against attacks.
Escaping
~~~~~~~~
When outputting any user input (either route variables GET/POST variables
obtained from the request), you will have to make sure to escape it correctly,
to prevent Cross-Site-Scripting attacks.
When outputting any user input, make sure to escape it correctly to prevent
Cross-Site-Scripting attacks.
* **Escaping HTML**: PHP provides the ``htmlspecialchars`` function for this.
Silex provides a shortcut ``escape`` method::
...
...
@@ -745,7 +709,7 @@ to prevent Cross-Site-Scripting attacks.
return "You provided the name {$app->escape($name)}.";
});
If you use the Twig template engine you should use its escaping or even
If you use the Twig template engine
,
you should use its escaping or even
auto-escaping mechanisms.
* **Escaping JSON**: If you want to provide data in JSON format you should
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment