Dependency Injection (DI) is a fantastic technique, but what if you what to use dependency injection in your legacy application. Fear not! As someone who as done this very thing, I will show how you can successful and incrementally add DI to any application. I will present a number of recipes and solutions to common problems and give a tour of the various PHP DI projects and how they can help.
This session introduces most well known design patterns to build PHP classes and objects that need to store and fetch data from a relational databases. The session will describe the difference between of the Active Record, the Table and Row Data Gateway and the Data Mapper pattern. We will also examine some technical advantages and drawbacks of these implementations. This talk will expose some of the best PHP tools, which ease database interactions and are built on top of these patterns.
Persistence is one of the most important part in a PHP project. Persisting data to a database came with PHP/FI and its MySQL support. From native extensions and PHP4 database abstraction libraries to PDO and modern ORM frameworks, you will (re)discover how persistence has evolved during the last decade. This talk will also introduce the future of data persistence with the growing success of alternative storage engines.
Silex is a brand new PHP 5.3 micro framework built on top of the Symfony2 de decoupled components. In this session, we will discover how to build and deploy powerful REST web services with such a micro framework and its embedded tools.
The first part of this talk will introduce the basics of the REST architecture. We fill focus on the main concepts of REST like HTTP methods, URIs and open formats like XML and JSON.
Then, we will discover how to deploy REST services using most of interesting Silex tools like database abstraction layer, template engine and input validation. We will also look at unit and functional testing frameworks with PHPUnit and HTTP caching with Edge Side Includes and Varnish support to improve performances.
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
As presented at ZendCon 2014, AmsterdamPHP, PHPBenelux 2014, Sweetlake PHP and PHP Northwest 2013, an overview of some different patterns for integrating and managing logic throughout your application.
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
Cette conférence présente deux grands motifs de conception : l'observateur et l'injection de dépendance. Ce sujet allie à la fois théorie et pratique. Le composant autonome EventDispatcher de Symfony ainsi que le conteneur d'injection de dépendance Pimple sont mis à l'honneur avec des exemples pratiques d'usage. Ces cas pratiques combinent du code de l'ORM Propel ainsi que le composant autonome Zend\Search\Lucene du Zend Framework 2
This session introduces most well known design patterns to build PHP classes and objects that need to store and fetch data from a relational databases. The session will describe the difference between of the Active Record, the Table and Row Data Gateway and the Data Mapper pattern. We will also examine some technical advantages and drawbacks of these implementations. This talk will expose some of the best PHP tools, which ease database interactions and are built on top of these patterns.
Persistence is one of the most important part in a PHP project. Persisting data to a database came with PHP/FI and its MySQL support. From native extensions and PHP4 database abstraction libraries to PDO and modern ORM frameworks, you will (re)discover how persistence has evolved during the last decade. This talk will also introduce the future of data persistence with the growing success of alternative storage engines.
Silex is a brand new PHP 5.3 micro framework built on top of the Symfony2 de decoupled components. In this session, we will discover how to build and deploy powerful REST web services with such a micro framework and its embedded tools.
The first part of this talk will introduce the basics of the REST architecture. We fill focus on the main concepts of REST like HTTP methods, URIs and open formats like XML and JSON.
Then, we will discover how to deploy REST services using most of interesting Silex tools like database abstraction layer, template engine and input validation. We will also look at unit and functional testing frameworks with PHPUnit and HTTP caching with Edge Side Includes and Varnish support to improve performances.
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
As presented at ZendCon 2014, AmsterdamPHP, PHPBenelux 2014, Sweetlake PHP and PHP Northwest 2013, an overview of some different patterns for integrating and managing logic throughout your application.
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
Cette conférence présente deux grands motifs de conception : l'observateur et l'injection de dépendance. Ce sujet allie à la fois théorie et pratique. Le composant autonome EventDispatcher de Symfony ainsi que le conteneur d'injection de dépendance Pimple sont mis à l'honneur avec des exemples pratiques d'usage. Ces cas pratiques combinent du code de l'ORM Propel ainsi que le composant autonome Zend\Search\Lucene du Zend Framework 2
By the sum of PHPUnit assertion power and Symfony2 functional testing tools the developer can obtain a deep control on the developed application.
Here you can find some suggestions on how to leverage that power.
Un gioco in cui vincono tutti o due piccioni con una fava ;)
Lavorare rivolti alla creazione di valore per il cliente e da questo ottenere una libreria quasi pronta per essere pubblicata
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. Making right decision about these investments is very tricky and the cost of wrong decisions might be crippling for both business and teams that support it.
Extreme Programming and Test Driven Development in particular are practices that are aiming at supporting development effort by making it easier to introduce change. That said, sometimes those tools can become a problem of its own when applied in the wrong way or for the wrong context. Understanding software cost forces is a very important skill of successful teams and something that helps understand how to apply XP and TDD in different contexts.
All projects start with a lot of enthusiasm. As many projects grow the technical debt gets bigger and the enthusiasm gets less. Almost any developer can develop a great project, but the key is maintaining an ever evolving application with minimal technical debt without loosing enthusiasm.
During this talk you will be taken on the journey of application design. The starting point is an application that looks fine but contains lots of potential pitfalls. We will address the problems and solve them with beautiful design. We end up with testable, nicely separated software with a clear intention.
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
Slides from my talk presented during Dutch PHP Conference in Amsterdam - 25 June 2016
More Domain-Driven Design related content at: https://domaincentric.net/
How do you create applications with an incredible level of extendability without losing readability in the process? What if there's a way to separate concerns not only on the code, but on the service definition level? This talk will explore structural and behavioural patterns and ways to enrich them through tricks of powerful dependency injection containers such as Symfony2 DIC component.
Your code sucks, let's fix it - DPC UnConRafael Dohms
How do you measure the quality of your code? Performance and testing are just one aspect of code, in order to meet deadlines and make maintenance quicker you also need your code to be readable, decoupled and generally easier to comprehend and work with. This talk will go over tips and exercises to help you identify trouble areas, refactor them and train you to write better code in future projects. Come make your code look and function better.
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. In this talk you will learn how to see, understand and game some of these forces in your favour.
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard ssertions like 'assertEquals()' or
'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
Have you ever wondered how all this CQRS / ES concepts could be applied to a PHP project? Let's take a look at some code of our last project: a warehouse management system.
This talk will show how we understand DDD and how we apply it at Ulabox, what changes in application's architecture and code when we apply CQRS and how to deal with event sourcing, when there're no persisted entities, only events that generate projections used in the read model.
Speaker: Manel Sellés (@manelselles), software engineer, DDD-TDD fan and Symfony Expert Certified by Sensiolabs. Currently developing enterprise logistics software at Ulabox.com
PHP 8.1 brings Enums, one of the most requested features in PHP.
Enums, or Enumerations, allow creating strict and type-safe structures for fixed values. An Enum structure can hold a number of values that can also be backed with integer or string values.
In this comprehensive session, we will discover what Enums are, why they are useful, how to apply them on our applications including Drupal, and things to watch out for when using Enums.
Audience
This session is for those who are familiar with modern PHP practices such as Object Oriented Programming, and principles such as Liskov Substitution principle. A quick introduction will be given to catch up to speed, but familiarity with such concepts can help a lot.
What you will learn
What are Enums.
Why Enums are useful.
How to use Enums
Migrating from magic constants/values to Enums.
Backed Enums and storing/fetching Enum values with a database.
Using Enums in a Drupal context.
Caveats when using Enums.
Author
Ayesh Karunaratne is the author of PHP.Watch (https://php.watch), where he provides in-depth articles and documents on PHP and latest changes to the language.
PHP 8.0: https://php.watch/versions/8.0
PHP 8.1: https://php.watch/versions/8.1
Enums: https://php.watch/versions/8.1/enums
Closing keynote, as presented at Codemotion 2014, LaraconEU 2014, Redevelop 2014, CodeConnexx 2013 and PHP North East 2014.
This presentation makes a reference to a reading list I received. For those interested, the release consists of most of the general classics, such as Gang Of Four "Design Patterns", The Pragmatic Programmer, Structure and Interpretation of Computer Programs, Domain Driven Design and a few others. The actual list remains tucked away in a box somewhere.
By the sum of PHPUnit assertion power and Symfony2 functional testing tools the developer can obtain a deep control on the developed application.
Here you can find some suggestions on how to leverage that power.
Un gioco in cui vincono tutti o due piccioni con una fava ;)
Lavorare rivolti alla creazione di valore per il cliente e da questo ottenere una libreria quasi pronta per essere pubblicata
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. Making right decision about these investments is very tricky and the cost of wrong decisions might be crippling for both business and teams that support it.
Extreme Programming and Test Driven Development in particular are practices that are aiming at supporting development effort by making it easier to introduce change. That said, sometimes those tools can become a problem of its own when applied in the wrong way or for the wrong context. Understanding software cost forces is a very important skill of successful teams and something that helps understand how to apply XP and TDD in different contexts.
All projects start with a lot of enthusiasm. As many projects grow the technical debt gets bigger and the enthusiasm gets less. Almost any developer can develop a great project, but the key is maintaining an ever evolving application with minimal technical debt without loosing enthusiasm.
During this talk you will be taken on the journey of application design. The starting point is an application that looks fine but contains lots of potential pitfalls. We will address the problems and solve them with beautiful design. We end up with testable, nicely separated software with a clear intention.
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
Slides from my talk presented during Dutch PHP Conference in Amsterdam - 25 June 2016
More Domain-Driven Design related content at: https://domaincentric.net/
How do you create applications with an incredible level of extendability without losing readability in the process? What if there's a way to separate concerns not only on the code, but on the service definition level? This talk will explore structural and behavioural patterns and ways to enrich them through tricks of powerful dependency injection containers such as Symfony2 DIC component.
Your code sucks, let's fix it - DPC UnConRafael Dohms
How do you measure the quality of your code? Performance and testing are just one aspect of code, in order to meet deadlines and make maintenance quicker you also need your code to be readable, decoupled and generally easier to comprehend and work with. This talk will go over tips and exercises to help you identify trouble areas, refactor them and train you to write better code in future projects. Come make your code look and function better.
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. In this talk you will learn how to see, understand and game some of these forces in your favour.
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard ssertions like 'assertEquals()' or
'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
Have you ever wondered how all this CQRS / ES concepts could be applied to a PHP project? Let's take a look at some code of our last project: a warehouse management system.
This talk will show how we understand DDD and how we apply it at Ulabox, what changes in application's architecture and code when we apply CQRS and how to deal with event sourcing, when there're no persisted entities, only events that generate projections used in the read model.
Speaker: Manel Sellés (@manelselles), software engineer, DDD-TDD fan and Symfony Expert Certified by Sensiolabs. Currently developing enterprise logistics software at Ulabox.com
PHP 8.1 brings Enums, one of the most requested features in PHP.
Enums, or Enumerations, allow creating strict and type-safe structures for fixed values. An Enum structure can hold a number of values that can also be backed with integer or string values.
In this comprehensive session, we will discover what Enums are, why they are useful, how to apply them on our applications including Drupal, and things to watch out for when using Enums.
Audience
This session is for those who are familiar with modern PHP practices such as Object Oriented Programming, and principles such as Liskov Substitution principle. A quick introduction will be given to catch up to speed, but familiarity with such concepts can help a lot.
What you will learn
What are Enums.
Why Enums are useful.
How to use Enums
Migrating from magic constants/values to Enums.
Backed Enums and storing/fetching Enum values with a database.
Using Enums in a Drupal context.
Caveats when using Enums.
Author
Ayesh Karunaratne is the author of PHP.Watch (https://php.watch), where he provides in-depth articles and documents on PHP and latest changes to the language.
PHP 8.0: https://php.watch/versions/8.0
PHP 8.1: https://php.watch/versions/8.1
Enums: https://php.watch/versions/8.1/enums
Closing keynote, as presented at Codemotion 2014, LaraconEU 2014, Redevelop 2014, CodeConnexx 2013 and PHP North East 2014.
This presentation makes a reference to a reading list I received. For those interested, the release consists of most of the general classics, such as Gang Of Four "Design Patterns", The Pragmatic Programmer, Structure and Interpretation of Computer Programs, Domain Driven Design and a few others. The actual list remains tucked away in a box somewhere.
Refactoring, Agile Entwicklung, Continuous Integration – all diese für nachhaltigen Erfolg wichtigen Vorgehensweisen setzen Erfahrung mit Unit Testing voraus. Abseits von den üblichen "Bowling"-Beispielen möchten wir gerne einen Crashkurs inkl. Best Practices für das erfolgreiche Unit Testing durchführen. Anhand eines Beispielprojekts auf Basis des Zend Frameworks werden wir nach der Installation von PHPUnit auf allen Notebooks gemeinsam eine kleine Applikation aufbauen, die durchgehend Test-driven entwickelt wird.
Writing readable code is one of the most important aspects of web development. A developer should write code which another human is able to understand without the help of too many comments.
This talk will show you how to tidy up your code and write readable PHP.
Est-ce que nous allons parler de gestion des ressources humaines au PHP tour ? Non, je vous vais vous parler des modèles anémiques et des modèles riches. Depuis des années frameworks et ORM nous conditionnent à utiliser des modèles anémiques, une classe avec de simples setters et getters. A travers l’histoire d’Estelle, une RH, qui veut une application pour gérer ses salariés, je vais vous montrer comment changer nos vieilles habitudes afin de nous focaliser sur le métier que nous implémentons. Nous verrons ensemble quels outils utiliser, comme par exemple, le design pattern command bus, l’opérateur NEW de doctrine pour vos Data Transfert Object dans une application Symfony.
Example de code : https://github.com/arnolanglade/code-me-hr
You’ve seen Kris’ open source libraries, but how does he tackle coding out an application? Walk through green fields with a Symfony expert as he takes his latest “next big thing” idea from the first line of code to a functional prototype. Learn design patterns and principles to guide your way in organizing your own code and take home some practical examples to kickstart your next project.
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSLiMasters
Augusto Pascutti, Software Engineer no Easy Taxi, fez a palestra "Melhorando a comunicação da API através de DSL", no PHP Experience 2016.
O iMasters PHP Experience 2016 aconteceu nos dias 21 e 22 de Março de 2015, no Hotel Tivoli em São Paulo-SP
http://phpexperience2016.imasters.com.br/
https://speakerdeck.com/willroth/50-laravel-tricks-in-50-minutes - origin
Laravel 5.1 raised the bar for framework documentation, but there's much, much more lurking beneath the surface. In this 50-minute session, we'll explore 50 (yes, 50!) high-leverage implementation tips & tricks that you just won't find in the docs: the IoC Container, Blade, Eloquent, Middleware, Routing, Commands, Queues, Events, Caching — we'll cover them all! Join us as we drink from the fire hose & learn to take advantage of everything that Laravel has to offer to build better software faster!
As presented at Dutch PHP Conference 2015, an introduction to command buses, how to implement your own in PHP and why they're both useful but unimportant.
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceIvan Chepurnyi
It is a pity, but I have to admit, that Magento 2 has issues in layout generation process. You'll learn during the talk about the benefits of compiling XML structures into PHP code, and even use the compilation of PHP code into PHP code to speed up your modules complex logic.
"Dependency injection" (DI) seems like one of those hot buzzwords that will solve all your problems. But what is DI really? How does it help keep code clean and maintainable? And how do you take a legacy codebase and rewrite it to take advantage of DI? This talk takes an application written without DI and walks through the steps for "injecting" DI into the code. Learn the difference between "dependency injection" and "dependency injection containers". See how DI makes things like event-driven architectures simple to implement. And learn how DI leads to code that is easier to debug and test.
Similar to Adding Dependency Injection to Legacy Applications (20)
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
17. class Status {
public function get($system) {
$client = new Zend_Http_Client();
$r = $client->setUri(SERVICE_URI)
->setParameterGet(compact('system'))
->request('GET');
if ($r->isSuccessful()) {
return $r->getBody();
}
return false;
}
}
18. Constructor
Injection
Vs.
Setter/Property
Injection
19. class StatusSetterInject{
protected $client;
public function setClient(Zend_Http_Client $client){
$this->client = $client;
}
public function get($system){
$r = $this->client->setUri(SERVICE_URI)
->setParameterGet(compact('system'))
->request('GET');
if ($r->isSuccessful()){
return $r->getBody();
}
return false;
}
}
20. class StatusConstructInject{
protected $client;
public function __construct(Zend_Http_Client $client){
$this->client = $client;
}
public function get($system){
$r = $this->client->setUri(SERVICE_URI)
->setParameterGet(compact('system'))
->request('GET');
if($r->isSuccessful()){
return $r->getBody();
}
return false;
}
}
22. class StatusInit{
protected $client;
public function __construct(Zend_Http_Client $client){
$this->client = $client;
$this->init();
}
public function init(){
//Left empty
}
public function get($system){
$r = $this->client->setUri(SERVICE_URI)
->setParameterGet(compact('system'))
->request('GET');
//...
}
}
24. class StatusConstructInjectOptional{
protected $client;
public function __construct(
Zend_Http_Client $client = null){
if($client === null){
$client = new Zend_Http_Client();
}
$this->client = $client;
}
public function get($system){
$r = $this->client->setUri(SERVICE_URI)
->setParameterGet(compact('system'))
->request('GET');
//...
}
}
25. class StatusSetterInjectOptional{
protected $client;
public function setClient(Zend_Http_Client $client){
$this->client = $client;
}
protected function getClient(){
if ($this->client === null){
$this->client = new Zend_Http_Client();
}
return $this->client;
}
public function get($system){
$r = $this->getClient()->setUri(SERVICE_URI)
->setParameterGet(compact('system'))
->request('GET');
//...
35. abstract class FactoryAbstract{
protected abstract function getClassName();
public function create(){
$class = $this->getClassName();
$argList = func_get_args();
if (count($argList) < 1){
return new $class;
}
$rClass = new ReflectionClass($class);
return $rClass->newInstanceArgs($argList);
}
}
36. function __autoload($class){
$classPath = str_replace('_', '/', $class);
$filePath = __DIR__."/src/$classPath.php";
if (file_exists($filePath))
return require $filePath;
if (substr($class, -7) !== 'Factory')
return;
$subName = substr($class, 0, -8);
eval("class $class extends FactoryAbstract{
protected function getClassName(){
return '$subName';
}
}");
}
44. abstract class Zend_View_Abstract
implements Zend_View_Interface
//...
public function registerHelper($helper, $name){
//...
if (!$helper instanceof Zend_View_Interface){
if (!method_exists($helper, $name)){
require_once 'Zend/View/Exception.php';
$e = new Zend_View_Exception(
'View helper must …');
$e->setView($this);
throw $e;
}
}
if (method_exists($helper, 'setView')){
$helper->setView($this);
}
//...
54. class Db{
protected function __construct(){}
protected function __clone(){}
public static function instance(){
static $instance = null;
if($instance === null){
$instance = new static();
}
return $instance;
}
}
56. class Registry{
protected static $reg = array();
public static function add($key, $value){
static::$reg[$key] = $value;
}
public static function get($key){
return static::$reg[$key];
}
}
57. class Registry{
protected static $reg = array();
public static function add($key, $value){
static::$reg[$key] = $value;
}
public static function get($key){
$value = static::$reg[$key];
if(is_callable($value)){
return $value();
}
return $value;
}
}
66. interface LoggerInterface{}
abstract class LoggerAbstract implements LoggerInterface{}
class LoggerEcho extends LoggerAbstract{}
class LoggerFile extends LoggerAbstract{}
class LoggerOddBall implements LoggerInterface{}
69. interface Logger{}
abstract class LoggerAbstract implements Logger{}
class LoggerEcho extends Logger{}
class LoggerFile extends Logger{}
class LoggerOddBall implements Logger{}
Welding customHitch interfaceRope a lot of workWelder – Flickr - F0t0Synthcogdogblog – tow hitch - flickr
DI should not be your goal, especially when it comes to adding DI to you’re legacy appsMaintainable codeQuality codeFlexible codeReusable codeNVJ – Flickr
Bang for the Buck!Not everything needs to have DI or fit the goal you are going afterIf you’re goal is testability and you are using ZF1 for example, not every plugin or helper you create maybe worth the time it would take to create unit tests for.If you are adding DI to a code base where not everyone is on-board with the concept. This will help you fall foul of the perception you are wasting time.Being a purest in legacy code may take you to an early grave.http://misternewuzer.deviantart.com/art/Pop-Bang-Warpath-119523671
What I hope to give to you are some new tools to add to your tool boxWhiteforgeflickr
The Hollywood principle in practiceYou’re code should not know what it’s doing in the grand schema of things It should not be aware of it’s contexthttp://www.flickr.com/photos/duke_raoul/2262882022/sizes/l/in/photostream/
Be careful, opinions vary on this topicBike shed question,It doesn’t matter when you are adding DI to legacy, because the answer is, what ever works for you right now.http://www.flickr.com/photos/sue_langford/4525633192/sizes/l/in/photostream/
A helper pattern that works well with constructor injection, when you expect people to extend the classhttp://www.flickr.com/photos/22212359@N06/2307645669/sizes/l/in/photostream/
This can get ugly with large dependency listsThat’s also a code smell that your object is trying to do too much
You can combine this with constructor injection also
showbiz kids - flickr
Mixed string with instance
If you so an string check you could combine this is injection of an object instance
Hollywood principle againIf you use a class name where polymorphism can’t be used then you are calling out to the global namespace.Polymorphism is the ability to switch or replace an object of one type with an object of another typehttp://www.flickr.com/photos/demonbaby/3788532381/sizes/o/in/photostream/
Many types and names (factory method, builder, containers)Dirty work happens hereNeed to inject the factory into the objects that needs to create objectsRamson – Flickr
This is a little tedious for simple things
CDEGlobal – Flickr
Need to be careful once you start to combine with other techniques
Need some class name conventionCreate the real one to overrideDon’t have to use eval
So I can inject an instanceI can inject a factoryBut when and how do I do thatThis is the real hard workMichael D. Dunn – flickr
Just a sophisticated factorySo we will just be building upon what we have already cover for factoriesPinkpurse - Flickr
DavidMenting – Flickr
Could be PHP, XML, ini, etc
DAN_DAN2 – Flickr
Remember this would be inside of a factoryDoesn't scale great, but not awful
If it walks like a duck and it talks like a duck, then it’s a duck!http://www.flickr.com/photos/shinyhappyworld/5475939747/sizes/l/in/photostream/
Code from ZF1Could go further and check type hits and param counts.Could become a mess if it’s used a lot. In PHP you will need to do some kind of introspection You can cache the result of the introspection based on class nameIn reality this is the most powerful model for decupling, but with great power come great opportunity to kill yourself
Try to wire the objects up with out a central configuration and without a hand coded factory for every non-trivial object
Code from a DI project I created
Well sudoZalgon – Flickr
Will also have to check inheritance tree for things like class level annotations
Used with auto wiring
If you process the annotations by creating a config object about the class, you can then cache that config object.
It not always possible or advisable to be 100% DI, especially but not right away.
Gives you global access and a shared instanceWill spread global access all over your codeBob.Fornal– Flickr
Hard to test without adding test hooks to reset, which is evil.
You can put anything you need in the registryAnyone can put or change the data in the registry
A little better than just a singleton. Something still has to fill it with class instances first. Could use anonymous function.
ilovememphis – Flickr
Like a fixed registry with builder code baked in.Still has an issue with testing, but solutions are less evilIf you’ve ever worked with ZF1 boot-strapper and resource plugins this is much like thatIt also is a model of making the service locator pluggable
cogdogblog – Flickr
Refactoring'sKaptain Kobold – Flickr
Don't call an interface an interface
Written, verbal, call a meeting, socialize it, lunch and learns. Give it time.