* kriswallsmith/kernel/shorter-bundle-names:
updated codebase to use shorter bundle names
[HttpKernel] updated component to work with shorter bundle names
[HttpKernel] updated Bundle::getName() to validate bundle class name and rtrim "Bundle"
Quote from HTTP (bis) spec (Part 2 - 5.1.1):
The Reason Phrase exists for the
sole purpose of providing a textual description associated with the
numeric status code, out of deference to earlier Internet application
protocols that were more frequently used with interactive text
clients. A client SHOULD ignore the content of the Reason Phrase.
The onCore* events are fired at some pre-defined points during the
handling of a request. At this is more important than the fact
that you can change things from the event.
* opensky/hotfix/test_client:
[HttpKernel] added test for uri change
[HttpKernel] got rid of url transformation into uri, as parse_url doesn't work with uris
The only missing part is ContainerAwareEventManager::addEventSubscriberService(),
because I'm not sure how to find out the class name of a service in the DIC.
Also, inline documentation of this code needs to be finished once it is accepted.
* hhamon/cookie_path_fix:
[Security] renamed Cookie::isHttponly() to Cookie::isHttpOnly()
[HttpKernel] renamed Cookie::isHttponly() to Cookie::isHttpOnly()
[BrowserKit] renamed Cookie::isHttponly() to Cookie::isHttpOnly()
[HttpFoundation] fix cookie path default value to / and added some new unit tests to cover the class
* digitalkaoz/httpkernel-debug:
[HttpKernel] added tests for debug stuff
[HttpKernel] reset handling if subject::handle throws an exception, otherwise it wouldnt be able to handle furthermore
Doctrine's EventManager implementation has several advantages over the
EventDispatcher implementation of Symfony2. Therefore I suggest that we
use their implementation.
Advantages:
* Event Listeners are objects, not callbacks. These objects have handler
methods that have the same name as the event. This helps a lot when
reading the code and makes the code for adding an event listener shorter.
* You can create Event Subscribers, which are event listeners with an
additional getSubscribedEvents() method. The benefit here is that the
code that registers the subscriber doesn't need to know about its
implementation.
* All events are defined in static Events classes, so users of IDEs benefit
of code completion
* The communication between the dispatching class of an event and all
listeners is done through a subclass of EventArgs. This subclass can be
tailored to the type of event. A constructor, setters and getters can be
implemented that verify the validity of the data set into the object.
See examples below.
* Because each event type corresponds to an EventArgs implementation,
developers of event listeners can look up the available EventArgs methods
and benefit of code completion.
* EventArgs::stopPropagation() is more flexible and (IMO) clearer to use
than notifyUntil(). Also, it is a concept that is also used in other
event implementations
Before:
class EventListener
{
public function handle(EventInterface $event, $data) { ... }
}
$dispatcher->connect('core.request', array($listener, 'handle'));
$dispatcher->notify('core.request', new Event(...));
After (with listeners):
final class Events
{
const onCoreRequest = 'onCoreRequest';
}
class EventListener
{
public function onCoreRequest(RequestEventArgs $eventArgs) { ... }
}
$evm->addEventListener(Events::onCoreRequest, $listener);
$evm->dispatchEvent(Events::onCoreRequest, new RequestEventArgs(...));
After (with subscribers):
class EventSubscriber
{
public function onCoreRequest(RequestEventArgs $eventArgs) { ... }
public function getSubscribedEvents()
{
return Events::onCoreRequest;
}
}
$evm->addEventSubscriber($subscriber);
$evm->dispatchEvent(Events::onCoreRequest, new RequestEventArgs(...));
Without this patch, if you call __toString() on a Response,
the content-type auto-detection would never be trigerred
as __toString() changes the default content-type.
As these files are just about optimizing the performance,
they are now part of the sandbox and the upcoming standard
Symfony distribution.
It should also make your IDE happier!
Fixes a bug in `Bundle::registerCommands` with console commands in sub-directories of `Command`. `MyBundle\Command\FooCommand` worked great, but with `MyBundle\Command\Bar\BazCommand` Bundle would try to register `MyBundle\CommandBar\BazCommand` instead.
This allows for better conventions and better error messages if you
use the wrong configuration alias in a config file.
This is also the first step for a bigger refactoring of how the configuration
works (see next commits).
* Bundle::registerExtensions() method has been renamed to Bundle::build()
* The "main" DIC extension must be renamed to the new convention to be
automatically registered:
SensioBlogBundle -> DependencyInjection\SensioBlogExtension
* The main DIC extension alias must follow the convention:
sensio_blog for SensioBlogBundle
* If you have more than one extension for a bundle (which should really
never be the case), they must be registered manually by overriding the
build() method
* If you use YAML or PHP for your configuration, renamed the following
configuration entry points in your configs:
app -> framework
webprofiler -> web_profiler
doctrine_odm -> doctrine_mongo_db
This reverts commit f53080860a.
Revert "[Router] config fixes"
This reverts commit 51beecc6f2.
Revert "moved duplicated files to a new Config component"
This reverts commit a8ec9b27f0.
Rules are :
- If one of the ESI has validation cache strategy, the whole page will be
forced to validate.
- In none of the ESI has validation, the response will feature a Cache-Control
directive with s-maxage value equals to the smallest TTL of ESIs.
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.)