A class in Symfony2 can be loaded by four different mechanisms:
* bootstrap.php: This file contains classes that are always required and
needed very early in the request handling;
* classes.php: This file contains classes that are always required and
managed by extensions via addClassesToCompile();
* MapFileClassLoader: This autoloader uses a map of class/file to load
classes (classes are managed by extensions via addClassesToAutoloadMap(),
and should contain often used classes);
* UniversalAutolaoder: This autoloader loads all other classes (it's the
slowest one).
The three notification methods do not return the Event instance anymore.
notify() does not return anything
notifyUntil() returns the returned value of the event that has processed the event
filter() returns the filtered value
Upgrading your listeners:
Listeners for notify() and filter() events: nothing to change
Listeners for notifyUntil() events:
Before:
$event->setReturnValue('foo');
return true;
After:
$event->setProcessed();
return 'foo';
If you notify events, the processing also need to be changed:
For filter() notifications: the filtered value is now available as
the returned value of the filter() method.
For notifyUntil() notifications:
Before:
$event = $dispatcher->notifyUntil($event);
if ($event->isProcessed()) {
$ret = $event->getReturnValue();
// do something with $ret
}
After:
$ret = $dispatcher->notifyUntil($event);
if ($event->isProcessed()) {
// do something with $ret
}
To benefit from the optimization, you need to change this line from your
autoload.php:
require_once $vendorDir.'/symfony/src/Symfony/Component/HttpFoundation/UniversalClassLoader.php';
to this one:
require_once $vendorDir.'/symfony/src/Symfony/Component/HttpKernel/bootstrap.php';
Notice that if you don't do this change, your app will in fact be slower than before.
Cache warmer will come in the next commits.
To warm up the cache on a production server, you can use
the cache:warmup command:
./app/console_prod cache:warmup
* The register() method on all listeners has been removed
* Instead, the information is now put directly in the DIC tag
For instance, a listener on core.request had this method:
public function register(EventDispatcher $dispatcher, $priority = 0)
{
$dispatcher->connect('core.response', array($this, 'filter'), $priority);
}
And this tag in the DIC configuration:
<tag name="kernel.listener" />
Now, it only has the following configuration:
<tag name="kernel.listener" event="core.response" method="filter" priority="0" />
The event and method attributes are now mandatory.
This adds lazy loading for firewall configurations. This is useful when you have multiple firewalls, only the firewalls which are actually needed to process the Request are initialized. So, your event dispatcher is not as costly to initialize anymore.
It also implements re-using of RequestMatchers if all matching rules are the same, and exposes the remaining rules which are already implemented by the request matcher (host, ip, methods) in the access-control section
Before I explain the changes, let's talk about the current state.
Before this patch, the registerBundleDirs() method returned an ordered (for
resource overloading) list of namespace prefixes and the path to their
location. Here are some problems with this approach:
* The paths set by this method and the paths configured for the autoloader
can be disconnected (leading to unexpected behaviors);
* A bundle outside these paths worked, but unexpected behavior can occur;
* Choosing a bundle namespace was limited to the registered namespace
prefixes, and their number should stay low enough (for performance reasons)
-- moreover the current Bundle\ and Application\ top namespaces does not
respect the standard rules for namespaces (first segment should be the
vendor name);
* Developers must understand the concept of "namespace prefixes" to
understand the overloading mechanism, which is one more thing to learn,
which is Symfony specific;
* Each time you want to get a resource that can be overloaded (a template for
instance), Symfony would have tried all namespace prefixes one after the
other until if finds a matching file. But that can be computed in advance
to reduce the overhead.
Another topic which was not really well addressed is how you can reference a
file/resource from a bundle (and take into account the possibility of
overloading). For instance, in the routing, you can import a file from a
bundle like this:
<import resource="FrameworkBundle/Resources/config/internal.xml" />
Again, this works only because we have a limited number of possible namespace
prefixes.
This patch addresses these problems and some more.
First, the registerBundleDirs() method has been removed. It means that you are
now free to use any namespace for your bundles. No need to have specific
prefixes anymore. You are also free to store them anywhere, in as many
directories as you want. You just need to be sure that they are autoloaded
correctly.
The bundle "name" is now always the short name of the bundle class (like
FrameworkBundle or SensioCasBundle). As the best practice is to prefix the
bundle name with the vendor name, it's up to the vendor to ensure that each
bundle name is unique. I insist that a bundle name must be unique. This was
the opposite before as two bundles with the same name was how Symfony2 found
inheritance.
A new getParent() method has been added to BundleInterface. It returns the
bundle name that the bundle overrides (this is optional of course). That way,
there is no ordering problem anymore as the inheritance tree is explicitely
defined by the bundle themselves.
So, with this system, we can easily have an inheritance tree like the
following:
FooBundle < MyFooBundle < MyCustomFooBundle
MyCustomFooBundle returns MyFooBundle for the getParent() method, and
MyFooBundle returns FooBundle.
If two bundles override the same bundle, an exception is thrown.
Based on the bundle name, you can now reference any resource with this
notation:
@FooBundle/Resources/config/routing.xml
@FooBundle/Controller/FooController.php
This notation is the input of the Kernel::locateResource() method, which
returns the location of the file (and of course it takes into account
overloading).
So, in the routing, you can now use the following:
<import resource="@FrameworkBundle/Resources/config/internal.xml" />
The template loading mechanism also use this method under the hood.
As a bonus, all the code that converts from internal notations to file names
(controller names: ControllerNameParser, template names: TemplateNameParser,
resource paths, ...) is now contained in several well-defined classes. The
same goes for the code that look for templates (TemplateLocator), routing
files (FileLocator), ...
As a side note, it is really easy to also support multiple-inheritance for a
bundle (for instance if a bundle returns an array of bundle names it extends).
However, this is not implemented in this patch as I'm not sure we want to
support that.
How to upgrade:
* Each bundle must now implement two new mandatory methods: getPath() and
getNamespace(), and optionally the getParent() method if the bundle extends
another one. Here is a common implementation for these methods:
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'MyFrameworkBundle';
}
/**
* {@inheritdoc}
*/
public function getNamespace()
{
return __NAMESPACE__;
}
/**
* {@inheritdoc}
*/
public function getPath()
{
return strtr(__DIR__, '\\', '/');
}
* The registerBundleDirs() can be removed from your Kernel class;
* If your code relies on getBundleDirs() or the kernel.bundle_dirs parameter,
it should be upgraded to use the new interface (see Doctrine commands for
many example of such a change);
* When referencing a bundle, you must now always use its name (no more \ or /
in bundle names) -- this transition was already done for most things
before, and now applies to the routing as well;
* Imports in routing files must be changed:
Before: <import resource="Sensio/CasBundle/Resources/config/internal.xml" />
After: <import resource="@SensioCasBundle/Resources/config/internal.xml" />
Let's take some examples to explain the change.
First, if you don't use any vendored bundles, this commit does not change anything.
So, let's say you use a FooBundle from Sensio. The files are stored under Bundle\Sensio\FooBundle.
And the Bundle class is Bundle\Sensio\FooBundle\SensioFooBundle.php.
Before the change, the bundle name ($bundle->getName()) would have returned 'FooBundle'.
Now it returns 'SensioFooBundle'.
Why does it matter? Well, it makes template names and controller names easier to read:
Before:
Template: Sensio\FooBundle:Bar:index.twig.html
Controller: Sensio\FooBundle:Bar:indexAction
After
Template: SensioFooBundle:Bar:index.twig.html
Controller: SensioFooBundle:Bar:indexAction
NB: Even if the change seems simple enough, the implementation is not. As finding
the namespace from the bundle class name is not trivial
NB2: If you don't follow the bundle name best practices, this will probably
leads to unexpected behaviors.
If a user was not authenticated and visited the logout path, a null value was passed to the handler's logout() method, resulting in a catchable fatal error.
Both HttpKernel and Security define a 403 exception:
* Symfony\Component\HttpKernel\Exception\ForbiddenHttpException
* Symfony\Component\Security\Exception\AccessDeniedException
The one in HttpKernel has been removed in favor of the Security one.
Previously, HttpKernel performed request-stashing. By moving this to the Kernel class, the request is now available immediately after the kernel becomes aware of it. If the kernel is allowed to boot lazily (during the first call to handle()), this also allows an actual master Request to be available during booting.
The old "request" service definition (with a bogus class name) can be replaced with a factory-aware definition that retrieves the request directly from the kernel.
The original HttpKernel class can be deleted, as it's request-stashing will be moved to the Kernel class. FrameworkBundle's list of compiled classes must also be modified to respect this change.
When an object has a "main" many relation with related "things" (objects,
parameters, ...), the method names are normalized:
* get()
* set()
* all()
* replace()
* remove()
* clear()
* isEmpty()
* add()
* register()
* count()
* keys()
The classes below follow this method naming convention:
* BrowserKit\CookieJar -> Cookie
* BrowserKit\History -> Request
* Console\Application -> Command
* Console\Application\Helper\HelperSet -> HelperInterface
* DependencyInjection\Container -> services
* DependencyInjection\ContainerBuilder -> services
* DependencyInjection\ParameterBag\ParameterBag -> parameters
* DependencyInjection\ParameterBag\FrozenParameterBag -> parameters
* DomCrawler\Form -> FormField
* EventDispatcher\Event -> parameters
* Form\FieldGroup -> Field
* HttpFoundation\HeaderBag -> headers
* HttpFoundation\ParameterBag -> parameters
* HttpFoundation\Session -> attributes
* HttpKernel\Profiler\Profiler -> DataCollectorInterface
* Routing\RouteCollection -> Route
* Security\Authentication\AuthenticationProviderManager -> AuthenticationProviderInterface
* Templating\Engine -> HelperInterface
* Translation\MessageCatalogue -> messages
The usage of these methods are only allowed when it is clear that there is a
main relation:
* a CookieJar has many Cookies;
* a Container has many services and many parameters (as services is the main
relation, we use the naming convention for this relation);
* a Console Input has many arguments and many options. There is no "main"
relation, and so the naming convention does not apply.
For many relations where the convention does not apply, the following methods
must be used instead (where XXX is the name of the related thing):
* get() -> getXXX()
* set() -> setXXX()
* all() -> getXXXs()
* replace() -> setXXXs()
* remove() -> removeXXX()
* clear() -> clearXXX()
* isEmpty() -> isEmptyXXX()
* add() -> addXXX()
* register() -> registerXXX()
* count() -> countXXX()
* keys()
* removed the __call() method in Container: it means that now, there is only
one way to get a service: via the get() method;
* removed the $shared variable in the dumped Container classes (we now use
the $services variable from the parent class directly -- this is where we
have a performance improvement);
* optimized the PHP Dumper output.
The PHP native cache limiter feature has been disabled as this is now managed
by the HeaderBag class directly instead (see below.)
The HeaderBag class uses the following rules to define a sensible and
convervative default value for the Response 'Cache-Control' header:
* If no cache header is defined ('Cache-Control', 'ETag', 'Last-Modified',
and 'Expires'), 'Cache-Control' is set to 'no-cache';
* If 'Cache-Control' is empty, its value is set to "private, max-age=0,
must-revalidate";
* But if at least one 'Cache-Control' directive is set, and no 'public' or
'private' directives have been explicitely added, Symfony2 adds the
'private' directive automatically (except when 's-maxage' is set.)
So, remember to explicitly add the 'public' directive to 'Cache-Control' when
you want shared caches to store your application resources:
// The Response is private by default
$response->setEtag($etag);
$response->setLastModified($date);
$response->setMaxAge(10);
// Change the Response to be public
$response->setPublic();
// Set cache settings in one call
$response->setCache(array(
'etag' => $etag,
'last_modified' => $date,
'max_age' => 10,
'public' => true,
));
Some explanations on how it works now:
* The Session is an optional dependency of the Request. If you create the
Request yourself (which is mandatory now in the front controller) and if
you don't inject a Session yourself (which is recommended if you want the
session to be configured via dependency injection), the Symfony2 Kernel
will associate the Session configured in the Container with the Request
automatically.
* When duplicating a request, the session is shared between the parent and
the child (that's because duplicated requests are sub-requests of the main
one most of the time.) Notice that when you use ::create(), the behavior is
the same as for the constructor; no session is attached to the Request.
* Symfony2 tries hard to not create a session cookie when it is not needed
but a Session object is always available (the cookie is only created when
"something" is stored in the session.)
* Symfony2 only starts a session when:
* A session already exists in the request ($_COOKIE[session_name()] is
defined -- this is done by RequestListener);
* There is something written in the session object (the cookie will be sent
to the Client).
* Notice that reading from the session does not start the session anymore (as
we don't need to start a new session to get the default values, and because
if a session exists, it has already been started by RequestListener.)