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
100
Symfony Internals
meandmymonkey
3
720
Divide and Conquer
meandmymonkey
1
600
Deptrac - Keep Your Architecture Clean
meandmymonkey
0
590
Introduction to Docker at PHPBenelux2015
meandmymonkey
3
780
Best Practices in Symfony2
meandmymonkey
0
320
Introduction to Docker at PHPNW2014
meandmymonkey
4
390
O(ops), Authentication!
meandmymonkey
4
770
Best Practices in Symfony2
meandmymonkey
15
1.7k
Other Decks in Programming
See All in Programming
카카오페이는 어떻게 수천만 결제를 처리할까? 우아한 결제 분산락 노하우
kakao
PRO
0
110
ActiveSupport::Notifications supporting instrumentation of Rails apps with OpenTelemetry
ymtdzzz
1
250
Less waste, more joy, and a lot more green: How Quarkus makes Java better
hollycummins
0
100
TypeScriptでライブラリとの依存を限定的にする方法
tutinoko
3
700
Duckdb-Wasmでローカルダッシュボードを作ってみた
nkforwork
0
130
ピラミッド、アイスクリームコーン、SMURF: 自動テストの最適バランスを求めて / Pyramid Ice-Cream-Cone and SMURF
twada
PRO
10
1.3k
3rd party scriptでもReactを使いたい! Preact + Reactのハイブリッド開発
righttouch
PRO
1
610
CSC509 Lecture 09
javiergs
PRO
0
140
Click-free releases & the making of a CLI app
oheyadam
2
120
エンジニアとして関わる要件と仕様(公開用)
murabayashi
0
300
macOS でできる リアルタイム動画像処理
biacco42
9
2.4k
距離関数を極める! / SESSIONS 2024
gam0022
0
290
Featured
See All Featured
Principles of Awesome APIs and How to Build Them.
keavy
126
17k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
26
2.1k
A designer walks into a library…
pauljervisheath
204
24k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
27
840
Building a Scalable Design System with Sketch
lauravandoore
459
33k
Measuring & Analyzing Core Web Vitals
bluesmoon
4
130
XXLCSS - How to scale CSS and keep your sanity
sugarenia
246
1.3M
Fashionably flexible responsive web design (full day workshop)
malarkey
405
65k
GraphQLとの向き合い方2022年版
quramy
43
13k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
109
49k
Designing Dashboards & Data Visualisations in Web Apps
destraynor
229
52k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
10
720
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