Symfony 4.2 services cheat sheet (1)
2020-03-01 207浏览
- 1.Services The way you can re-use code in Symfony Byhttps://andreiabohner.orgThecommand:$ php bin/consoledebug:autowiringFetching and using services 4.2 There are 2ways: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.yamlservices:'>services: