
Symfony tips I’ve learn recently
I always read a lot of articles/tweets about Symfony and Php development. I often try new things to improve my code quality. Here are some things I’ve found recently and will try to set up in my projects.
Define private services
Service have a visibility status. By default, they are set as visible. If they’re not visible, container won’t return them. So why set them as private ? Because it definitely demonstrate to other project developper that they can’t use it as they wan’t. They can’t call it as they wan’t, it can only be injected into others service. It can also provide a small performance boost if they’re never injected into others services.
Better use of exceptions
In some case, we have to catch exception incoming from other part bundle. They can throw none-qualified exception, mostly the php \Exception that we all know.
try {
$this->container->doingThings();} catch (\Exception $e) {
$this->logger->warn('doingThings: ' . $e->getMessage());}
Exception is catch, message is logged, but… who is sending this fucking exception ? Help yourself using Php Exception methods:
try {
$this->container->doingThings();} catch (\Exception $e) {
$this->logger->warn('doingThings: ' . $e->getMessage() ' in ' . $e->getFile() . ':' . $e->getLine());}
Use factory with the Symfony DIC
If your using your own factory, you can directly ask your factory to generate services. You can use the factory_service with the factory_method property to indicate how to use it.
For exemple, you can use the doctrine factory to get a service for each of your entity repositories.
services:
client_repository:
class: Doctrine\Common\Persistence\ObjectRepository
factory_service: doctrine
factory_method: getRepository
public: false
arguments:
- "ACME\AcmeBundle\Entity\Article"
It can also be quickly define using this:
services:
client_repository:
class: ArticleManager
factory: ["@article_manager.factory", createArticleManager]
arguments:
- "ACME\AcmeBundle\Entity\Article"
Use static property to store array
With the recent improvement of composer performance, I’ve discover that OPCache work very well with static arrays. Instead of initializing big arrays listing in constructor, use static array can have a signifiant impact on performance.
Then you can get these static arrays using this syntax:
ArticleCategoryProvider::$listing;