Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Inside the Symfony DIC and Config
Search
Andreas Hucks
January 25, 2013
Programming
3
840
Inside the Symfony DIC and Config
Slides for my Symfony workshop at PHPBenelux 2013
Andreas Hucks
January 25, 2013
Tweet
Share
More Decks by Andreas Hucks
See All by Andreas Hucks
Divide and Conquer (LonghornPHP 2019)
meandmymonkey
0
110
Symfony Internals
meandmymonkey
3
740
Divide and Conquer
meandmymonkey
1
610
Deptrac - Keep Your Architecture Clean
meandmymonkey
0
590
Introduction to Docker at PHPBenelux2015
meandmymonkey
3
790
Best Practices in Symfony2
meandmymonkey
0
320
Introduction to Docker at PHPNW2014
meandmymonkey
4
390
O(ops), Authentication!
meandmymonkey
4
780
Best Practices in Symfony2
meandmymonkey
15
1.7k
Other Decks in Programming
See All in Programming
ドメインイベント増えすぎ問題
h0r15h0
1
220
testcontainers のススメ
sgash708
1
120
あれやってみてー駆動から成長を加速させる / areyattemite-driven
nashiusagi
1
200
命名をリントする
chiroruxx
1
390
As an Engineers, let's build the CRM system via LINE Official Account 2.0
clonn
1
670
Beyond ORM
77web
2
330
たのしいparse.y
ydah
3
120
PHPとAPI Platformで作る本格的なWeb APIアプリケーション(入門編) / phpcon 2024 Intro to API Platform
ttskch
0
150
Go の GC の不得意な部分を克服したい
taiyow
2
770
プロダクトの品質に コミットする / Commit to Product Quality
pekepek
2
770
Webエンジニア主体のモバイルチームの 生産性を高く保つためにやったこと
igreenwood
0
330
Stackless и stackful? Корутины и асинхронность в Go
lamodatech
0
690
Featured
See All Featured
Music & Morning Musume
bryan
46
6.2k
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
330
21k
Unsuck your backbone
ammeep
669
57k
Why Our Code Smells
bkeepers
PRO
335
57k
Bootstrapping a Software Product
garrettdimon
PRO
305
110k
Making Projects Easy
brettharned
116
5.9k
StorybookのUI Testing Handbookを読んだ
zakiyama
27
5.3k
Scaling GitHub
holman
458
140k
Rebuilding a faster, lazier Slack
samanthasiow
79
8.7k
How GitHub (no longer) Works
holman
311
140k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
280
13k
Building Applications with DynamoDB
mza
91
6.1k
Transcript
None
Symfony DIC and Configuration
Andreas Hucks @meandmymonkey Senior Developer, Trainer, Consultant SensioLabs Deutschland
The Project:
€
http://goo.gl/rS06X
Life without Dependency Injection
class Logger { public function log($message, $level =
'INFO') { $formatter = new XmlFormatter(); $log = $formatter-‐>format( $message, $level ); $this-‐>writeLog($log); } }
Problems?
class Logger { function __construct(FormatterInterface $formatter) {
$this-‐>formatter = $formatter; } [...] }
class Logger { [...] public function
log($message, $level = 'INFO') { $log = $this-‐>formatter-‐>format( $message, $level ); $this-‐>writeLog($log); } }
Alternative: Setter Injection
class Logger { [...] function setFormatter(FormatterInterface
$formatter) { $this-‐>formatter = $formatter; } [...] }
“Dependency Injection is where components are given their dependencies through
their constructors, methods, or directly into fields.”
Interfacing with the Webservice
interface ExchangeRatesInterface { /**
* @return array */ public function getRates(); /** * @param string $currency * @return float */ public function getRate($currency); }
interface AdapterInterface { /**
* @return string */ public function getRawData(); }
interface ParserInterface { /**
* @param string $rawData * @return array */ public function parse($rawData); }
Task Implement class ExchangeRates using MockAdapter and XmlParser. Generate output
using ExchangeRatesCommand .
The Service Container
The Service Container is simply a PHP object that manages
the instantiation of services.
$container-‐>get('logger'); $container-‐>getParameter('logger.class');
Vocabulary Elements
service An object managed by the Dependency Injection Container.
argument A parameter given by the DIC to a service,
via the constructor or a mutator method (setter).
parameter A configuration value.
<service id="sensio.logger" class="Sensio\Logger" > <!-‐-‐
Constructor arguments -‐-‐> <argument>/path/to/app/logs/app.log</argument> <argument type="service" id="sensio.logger.xml_formatter" /> <!-‐-‐ Methods to call -‐-‐> <call method="setDefaultSeverity"> <argument>DEBUG</argument> </call> <!-‐-‐ Tags -‐-‐> <tag name="tools.logger" /> </service>
Vocabulary Attributes
id The service identifier or name
class The service class to instantiate
alias An alias name for this service
public Set to false to make the service private and
used internally
<service id="sensio.logger" class="Sensio\Logger" > <!-‐-‐
Constructor arguments -‐-‐> <argument>/path/to/app/logs/app.log</argument> <argument type="service" id="sensio.logger.xml_formatter" /> <!-‐-‐ Methods to call -‐-‐> <call method="setDefaultSeverity"> <argument>DEBUG</argument> </call> <!-‐-‐ Tags -‐-‐> <tag name="tools.logger" /> </service>
Vocabulary Service Elements
argument An argument to pass to a method (constructor or
setter)
call A method to call on the newly created object
tag A tag to attach to the service definition
<service id="sensio.logger" class="Sensio\Logger" > <!-‐-‐
Constructor arguments -‐-‐> <argument>/path/to/app/logs/app.log</argument> <argument type="service" id="sensio.logger.xml_formatter" /> <!-‐-‐ Methods to call -‐-‐> <call method="setDefaultSeverity"> <argument>DEBUG</argument> </call> <!-‐-‐ Tags -‐-‐> <tag name="tools.logger" /> </service>
Vocabulary Argument Attributes
type Define the nature of the argument. Allowed values: string,
constant, collection or service
id The service name, if the argument is a service
key The argument key when dealing with the collection type
<service id="sensio.logger" class="Sensio\Logger" > <!-‐-‐
Constructor arguments -‐-‐> <argument>/path/to/app/logs/app.log</argument> <argument type="service" id="sensio.logger.xml_formatter" /> <!-‐-‐ Methods to call -‐-‐> <call method="setDefaultSeverity"> <argument>DEBUG</argument> </call> <!-‐-‐ Tags -‐-‐> <tag name="tools.logger" /> </service>
http://goo.gl/FNJ9H
Task Write a container configuration!
Configuration
public function load( array $configs, ContainerBuilder
$container ) { $configuration = new Configuration(); $config = $this -‐>processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader( $container, new FileLocator(__DIR__.'/../Resources/config') ); $loader-‐>load('exchangerates.xml'); }
Array ( [0] => Array (
[exchange_rates] => Array ( [curl] => Array ( [CURLOPT_TIMEOUT] => 5 ) ) ) [1] => Array ( [exchange_rates] => Array ( [curl] => Array ( [CURLOPT_TIMEOUT] => 10, [CURLOPT_PROXY] => http:// localhost:8888 ) ) ) )
Array ( [exchange_rates] => Array (
[curl] => Array ( [CURLOPT_TIMEOUT] => 10 [CURLOPT_PROXY] => http://localhost:8888 ) [endpoint] => http://www.ecb.europa.eu/stats... ) )
class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder()
{ $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder>root('acme_dic_workshop'); $rootNode -‐>children() -‐>scalarNode('some_config_var') -‐>isRequired() -‐>defaultValue('foo') -‐>end() -‐>end(); return $treeBuilder; } }
-‐>scalarNode(‘some_url') -‐>isRequired() -‐>cannotBeEmpty() -‐>validate() -‐>ifTrue(function($value)
{ return !filter_var($value, \FILTER_VALIDATE_URL); }) -‐>thenInvalid('Not a valid url.') -‐>end() -‐>end()
http://goo.gl/8sa6Q
Thanks! https://joind.in/7778