Questions about learning Symfony
1、Can a service only be retrieved from the container if its class is explicitly defined in services.yaml?
No.
A service can be retrieved from the container in two cases:
*1. Explicit definition in services.yaml. *
If the class is not in a PRS-4 autoload directory or its constructor arguments have to be declared mannually, the service class has to be defined in services.yaml.
2. Implicit(Auto-registeration)
The class is in a PSR-4 autoload directory AND Not excluded in services.yaml
2、Does the #[Route]Attribute Require the Controller to Be in src/Controller?
No.
Symfony’s #[Route]attribute works regardless of where the controller is located, as long as:
- The class is registered as a service (auto-registered via PSR-4 autoloading or explicitly defined in services.yaml).
- The route is properly configured in Symfony’s routing system.
3. Does Symfony’s #[Route]Attribute Have a Fallback Mechanism?
No. The #[Route]attribute itself does not have a built-in fallback mechanism. However, you can implement fallback behavior in Symfony using:
1. Route priorities (e.g., /blog/{slug}vs. /blog/list).
#[Route('/blog/{slug}', name: 'blog_show')]
public function show(string $slug): Response { ... }
#[Route('/blog/list', name: 'blog_list')]
public function list(): Response { ... }
A request to /blog/list match blog_list, not blog_show. However, /blog/other_list match blog_show.
#[Route('/{any}', name: 'fallback', priority: -10)]
public function fallback(): Response
{
// Handle 404 or redirect
throw $this->createNotFoundException();
}
Place this last (low priority) to avoid overriding other routes.
2. Custom route conditions (e.g., requirements, methods).
3. Event listeners (e.g., kernel.exceptionfor 404 handling).
4. How to custom route conditions? Give me an example.
5. Service object gotten by the container is a singleton object?
YES.
By default, the service object obtained from the container is a singleton. However, the object is reset per each request. Obviously, the service is stateless.
6. In my legacy application, there are many global variables. How to handle them in Symfony?
Use a factory to create them and pass DI(Dependency Injection) as contructor arugments to use them somewhere else.

浙公网安备 33010602011771号