Symfony Services Cheat Sheet

如果无法正常显示,请先停止浏览器的去广告插件。
分享至:
1. Services The way you can re-use code in Symfony By https://andreiabohner.org The command: $ php bin/console debug:autowiring Fetching and using services 4.2 There are 2 ways: can be used as type-hints in your methods/constructors 1. Autowirable services all services you create are autowirable Service Id Using a service In your controller, or in your own classes, you can "ask" for a service from the container by type-hinting an argument with the service's class or interface name. // src/Controller/ProductController.php Symfony will automatically pass the service object matching this type /** * @Route("/products") */ public function list( LoggerInterface $logger ) { $logger ->info('Look! I just used a service'); // ... } Adding dependencies in your service use Symfony\Component\Cache\Adapter\ AdapterInterface ; class MyService { private $cache ; Just pass them via constructor! The constructor’s arguments are autowired! public function __construct( AdapterInterface $cache ) { $this->cache = $cache ; } // ... when there´s more than one type hint for one service id, you can use either to get the exact same object Service Type Hint cache.app A service is just a class that does work! When you create your services (you can name it and put the code wherever you want) they are also automatically added in the container and available for autowiring! use Psr\Log\LoggerInterface ; Some autowirable services available Internally, each service has a unique name, or "id" By default , Creating a service list all services available for autowiring CacheItemPoolInterface AdapterInterface cache.app.simple CacheInterface doctrine.dbal.default_connection Connection service_container ContainerInterface debug.event_dispatcher EventDispatcherInterface debug.file_link_formatter FileLinkFormatter doctrine ManagerRegistry doctrine.orm.default_entity_manager EntityManagerInterface file_locator FileLocator filesystem Filesystem http_kernel HttpKernelInterface kernel KernelInterface monolog.logger LoggerInterface doctrine.orm.default_entity_manager ObjectManager annotations.cached_reader Reader parameter_bag ParameterBagInterface ContainerBagInterface request_stack RequestStack router.default UrlGeneratorInterface UrlMatcherInterface RequestContextAwareInterface RouterInterface router.request_context RequestContext serializer DecoderInterface EncoderInterface SerializerInterface NormalizerInterface DenormalizerInterface serializer.normalizer.object ObjectNormalizer session.handler SessionHandlerInterface service_container ContainerInterface session SessionInterface session.flash_bag FlashBagInterface session.storage.native SessionStorageInterface twig Twig_Environment Environment } 2. Explicitly configuring services and arguments # config/services.yaml services: Fetching a non-standard service service's id site_update_manager.superadmin : class: App\Updates\SiteUpdateManager autowire: false manually arguments: - '@App\Service\MessageGenerator' wire all - '@mailer' arguments - 'superadmin@example.com' site_update_manager.normal_users: class: App\Updates\SiteUpdateManager autowire: false arguments: - '@App\Service\MessageGenerator' - '@mailer' - 'contact@example.com' Access core services that cannot be autowired in your service via arguments: disable autowire for this service services: App\Service\MyService: arguments: $logger: '@monolog.logger.email ' @ - used to pass the service with that id Create an alias , so if you type-hint SiteUpdateManager , the site_update_manager.superadmin will be used App\Updates\ SiteUpdateManager : '@site_update_manager.superadmin '
2. By https://andreiabohner.org A class that does work Services all services are shared by default (i.e., each time you retrieve the service, you'll get the same instance ) Default configuration for services 4.2 All configurations below comes standard with every new Symfony project config under services will affect all services in the application default config values that should be # config/services.yaml applied to all services registered in this file services: automatically injects dependencies _defaults: in your services autowire : true automatically registers your services allows optimizing the container by removing unused autoconfigure : true as commands, fetching services directly from the container public : false event subscribers, ... via $container->get() won't work makes classes in src/ available to be used as services, this creates a service per class whose id is the FQCN services; App\: can be any valid glob pattern resource : '../src/*' exclude : '../src/{Entity,Migrations,Tests,Kernel.php}' is responsible for instantiating all the services Service Container where all services live! When you start a Symfony app, your container already contains many services. Services are never instantiated until, and unless, someone asks for them. Each service in the container is instantiated a maximum of once per request. E.g. of services: log security email cache database session Other configuration for services # config/services.yaml services: anonymous service: App\Foo: - prevent a service being - don't define an ID arguments: - created where is used - !service class: App\AnonymousBar deprecating a service App\Service\OldService: deprecated : The "%service_id%" is deprecated since 2.8 and will be removed in 3.0. App\SomeNonSharedService: shared : false non shared service: whenever you request the App\SomeNonSharedService, you will always get a new instance App\Service\EmailHelper: autowire : false you can put the bind key under _defaults , services , or a specific service used as a dependency of other services disable autowire to this service (override the default config just for this service) bind : $emailLogger: '@monolog.logger.email ' Some\Service: '@some.service' you can bind by: - argument name - class or interface - both above if find any argument named $emailLogger , the monolog.logger.email will be passed to it public function __construct(LoggerInterface $emailLogger) { $this->logger = $emailLogger; } Console $ php bin/console debug:autowiring show all services available for autowiring $ php bin/console debug:container full list of services available in the container $ php bin/console debug:container 'App\Service\Mailer' detailed info about a single service (you can use the service id too) $ php bin/console debug:container 'App\Service\Mailer' --show-arguments show the service arguments $ php bin/console debug:container --show-hidden display “hidden services” (whose ID starts with a dot)

trang chủ - Wiki
Copyright © 2011-2024 iteam. Current version is 2.137.3. UTC+08:00, 2024-11-28 21:36
浙ICP备14020137号-1 $bản đồ khách truy cập$