SlideShare a Scribd company logo
1 of 92
Download to read offline
Laravel Design Patterns
About Me
Bobby Bouwmann
@bobbybouwmann
Enrise -Code Cuisine
markdownmail.com
Laracasts
Laravel Design Patterns
Daily Design Patterns
What are Design Patterns?
Design Patterns are ...
Recipes for building maintainable code
Be your own Chef
Using the boundaries of Design Pattern
Why use Design Patterns?
— Provides a way to solve issues related to software development using
a proven solution
— Makes communication between developer more efficient
Why use Design Patterns?
— There is no"silver bullet"for using design pattern,each project and
situation is different
Maintainable Code
Maintainable Code
— Understandable
— Intuitive
— Adaptable
— Extendable
— Debuggable
Maintainable Code
— Don't Repeat Yourself
— Keep It Simple Stupid
Design Pattern Time
Design Pattern types
— Creational Patterns
— Structural Patterns
— Behavioural Patterns
Creational Patterns
— Class instantiation
— Hiding the creation logic
— Examples: Factory,Builder,Prototype,Singleton
Structural Patterns
— Composition between objects
— Usages of interfaces,abstract classes
— Examples: Adapter,Bridge,Decorator,Facade,Proxy
Behavioural Patterns
— Communication between objects
— Usages of mostly interfaces
— Examples: Command,Iterator,Observer,State,Strategy
Design Patterns in Laravel
— Factory Pattern
— Builder (Manager) Pattern
— Strategy Pattern
— Provider Pattern
— Repository Pattern
— Iterator Pattern
— Singleton Pattern
— Presenter Pattern
Design Patterns in Laravel
— Factory Pattern
— Builder (Manager) Pattern
— Strategy Pattern
— Provider Pattern
Factory Pattern
Factory Pattern
Provides an interface for creating objects
without specifying their concrete classes.
Factory Pattern
— Decouples code
— Factory is responsible for creating objects,not the client
— Multiple clients call the same factory,one place for changes
— Easier to test,easy to mock and isolate
Factory Pattern Example
interface PizzaFactoryContract
{
public function make(array $toppings = []): Pizza;
}
class PizzaFactory implements PizzaFactoryContract
{
public function make(array $toppings = []): Pizza
{
return new Pizza($toppings);
}
}
$pizza = (new PizzaFactory)->make(['chicken', 'onion']);
Factory Pattern Laravel Example
class PostsController
{
public function index(): IlluminateViewView
{
$posts = Post::all();
return view('posts.index', ['posts' => $posts]);
}
}
// IlluminateFoundationhelpers.php
/**
* @return IlluminateViewView|IlluminateContractsViewFactory
*/
function view($view = null, $data = [], $mergeData = [])
{
$factory = app(ViewFactory::class);
if (func_num_args() === 0) {
return $factory;
}
return $factory->make($view, $data, $mergeData);
}
/**
* Get the evaluated view contents for the given view.
*
* @return IlluminateContractsViewView
*/
public function make($view, $data = [], $mergeData = [])
{
$path = $this->finder->find(
$view = $this->normalizeName($view)
);
$data = array_merge($mergeData, $this->parseData($data));
return tap($this->viewInstance($view, $path, $data), function ($view) {
$this->callCreator($view);
});
}
/**
* Create a new view instance from the given arguments.
*
* @return IlluminateContractsViewView
*/
protected function viewInstance($view, $path, $data)
{
return new View($this, $this->getEngineFromPath($path), $view, $path, $data);
}
/**
* Create a new Validator instance.
*
* @return IlluminateValidationValidator
*/
public function make(array $data, array $rules, array $messages = [], array $customAttributes = [])
{
$validator = $this->resolve(
$data, $rules, $messages, $customAttributes
);
$this->addExtensions($validator);
return $validator;
}
/**
* Resolve a new Validator instance.
*
* @return IlluminateValidationValidator
*/
protected function resolve(array $data, array $rules, array $messages, array $customAttributes)
{
if (is_null($this->resolver)) {
return new Validator($this->translator, $data, $rules, $messages, $customAttributes);
}
return call_user_func($this->resolver, $this->translator, $data, $rules, $messages, $customAttributes);
}
Builder (Manager) Pattern
Builder (Manager) Pattern
Builds complex objects step by step.It can return different objects
based on the given data.
Builder (Manager) Pattern
— Decouples code
— Focuses on building complex objects step by step and returns them
— Has functionality to decide which objects should be returned
Builder Pattern Example
class PizzaBuilder
{
public function make(PizzaBuilderInterface $pizza): Pizza
{
// Returns object of type Pizza
}
}
class PizzaBuilder
{
public function make(PizzaBuilderInterface $pizza): Pizza
{
$pizza->prepare();
$pizza->applyToppings();
$pizza->bake();
return $pizza;
}
}
interface PizzaBuilderInterface
{
public function prepare(): Pizza;
public function applyToppings(): Pizza;
public function bake(): Pizza;
}
class MargarithaBuilder implements PizzaBuilderInterface
{
protected $pizza;
public function prepare(): Pizza
{
$this->pizza = new Pizza();
return $this->pizza;
}
public function applyToppings(): Pizza
{
$this->pizza->setToppings(['cheese', 'tomato']);
return $this->pizza;
}
public function bake(): Pizza
{
$this->pizza->setBakingTemperature(180);
$this->pizza->setBakingMinutes(8);
return $this->pizza;
}
}
class PizzaBuilder
{
public function make(PizzaBuilderInterface $pizza): Pizza
{
return $pizza
->prepare();
->applyToppings();
->bake();
}
}
// Create a PizzaBuilder
$pizzaBuilder = new PizzaBuilder;
// Create pizza using Builder which returns Pizza instance
$pizza = $pizzaBuilder->make(new MargarithaBuilder());
class ChickenBuilder implements PizzaBuilderInterface
{
protected $pizza;
public function prepare(): Pizza
{
$this->pizza = new Pizza();
return $this->pizza;
}
public function applyToppings(): Pizza
{
$this->pizza->setToppings(['cheese', 'tomato', 'chicken', 'corn']);
return $this->pizza;
}
public function bake(): Pizza
{
$this->pizza->setBakingTemperature(200)
$this->pizza->setBakingMinutes(8);
return $this->pizza;
}
}
class PizzaBuilder
{
public function make(PizzaBuilderInterface $pizza): Pizza
{
return $pizza
->prepare()
->applyToppings()
->bake();
}
}
$pizzaBuilder = new PizzaBuilder;
$pizzaOne = $pizzaBuilder->make(new MargarithaBuilder());
$pizzaTwo = $pizzaBuilder->make(new ChickenBuilder());
Builder Pattern Laravel
class PizzaManager extends IlluminateSupportManager
{
public function getDefaultDriver()
{
return 'margaritha';
}
public function createMargarithaDriver(): PizzaBuilderInterface
{
return new MargarithaBuilder();
}
public function createChickenPizzaDriver(): PizzaBuilderInterface
{
return new ChickenPizzaBuilder();
}
}
public function driver($driver = null)
{
$driver = $driver ?: $this->getDefaultDriver();
// If the given driver has not been created before, we will create the instances
// here and cache it so we can return it next time very quickly. If there is
// already a driver created by this name, we'll just return that instance.
if (! isset($this->drivers[$driver])) {
$this->drivers[$driver] = $this->createDriver($driver);
}
return $this->drivers[$driver];
}
protected function createDriver($driver)
{
// We'll check to see if a creator method exists for the given driver. If not we
// will check for a custom driver creator, which allows developers to create
// drivers using their own customized driver creator Closure to create it.
if (isset($this->customCreators[$driver])) {
return $this->callCustomCreator($driver);
} else {
$method = 'create' . Str::studly($driver) . 'Driver';
if (method_exists($this, $method)) {
return $this->$method();
}
}
throw new InvalidArgumentException("Driver [$driver] not supported.");
}
class PizzaManager extends IlluminateSupportManager
{
public function getDefaultDriver()
{
return 'margaritha';
}
public function createMargarithaDriver(): PizzaBuilderInterface
{
return new MargarithaBuilder();
}
}
$manager = new PizzaManager();
// MargarithaBuilder implementing PizzaBuilderInterface
$builder = $manager->driver('margaritha');
$pizza = $builder->make(); // Pizza
// IlluminateMailTransportManager
class TransportManager extends Manager
{
protected function createSmtpDriver()
{
// Code for building up a SmtpTransport class
}
protected function createMailgunDriver()
{
// Code for building up a MailgunTransport class
}
protected function createSparkpostDriver()
{
// Code for building up a SparkpostTransport class
}
protected function createLogDriver()
{
// Code for building up a LogTransport class
}
}
class TransportManager extends Manager
{
public function getDefaultDriver()
{
return $this->app['config']['mail.driver'];
}
// All create{$driver}Driver methods
}
// config/mail.php
'driver' => env('MAIL_DRIVER', 'smtp'),
// config/mail.php
'driver' => env('MAIL_DRIVER', 'smtp'),
// IlluminateMailTransportManager
createSmtpDriver()
// config/mail.php
'driver' => env('MAIL_DRIVER', 'smtp'),
// IlluminateMailTransportManager
createSmtpDriver()
// app/Http/Controllers/RegisterController
Mail::to($user)
->send(new UserRegistered($user));
Laravel Manager Pattern Examples
IlluminateAuthAuthManager
IlluminateBroadcastingBroadcastManager
IlluminateCacheCacheManager
IlluminateFilesystemFilesystemManager
IlluminateMailTransportManager
IlluminateNotificationsChannelManager
IlluminateQueueQueueManager
IlluminateSessionSessionManager
Strategy Pattern
Strategy Pattern
Defines a familiy of algorithms that are
interchangeable
Strategy Pattern
Program to an interface, not an
implementation.
Strategy Pattern Example
interface DeliveryStrategy
{
public function deliver(Address $address);
}
interface DeliveryStrategy
{
public function deliver(Address $address);
}
class BikeDelivery implements DeliveryStrategy
{
public function deliver(Address $address):
{
$route = new BikeRoute($address);
echo $route->calculateCosts();
echo $route->calculateDeliveryTime();
}
}
class PizzaDelivery
{
public function deliverPizza(DeliveryStrategy $strategy, Address $address)
{
return $strategy->deliver($address);
}
}
$address = new Address('Meer en Vaart 300, Amsterdam');
$delivery = new PizzaDelivery();
$delivery->deliver(new BikeDelivery(), $address);
class DroneDelivery implements DeliveryStrategy
{
public function deliver(Address $address):
{
$route = new DroneRoute($address);
echo $route->calculateCosts();
echo $route->calculateFlyTime();
}
}
class PizzaDelivery
{
public function deliverPizza(DeliveryStrategy $strategy, Address $address)
{
return $strategy->deliver($address);
}
}
$address = new Address('Meer en Vaart 300, Amsterdam');
$delivery = new PizzaDelivery();
$delivery->deliver(new BikeDelivery(), $address);
$delivery->deliver(new DroneDelivery(), $address);
Strategy Pattern Laravel Example
<?php
namespace IlluminateContractsEncryption;
interface Encrypter
{
/**
* Encrypt the given value.
*
* @param string $value
* @param bool $serialize
* @return string
*/
public function encrypt($value, $serialize = true);
/**
* Decrypt the given value.
*
* @param string $payload
* @param bool $unserialize
* @return string
*/
public function decrypt($payload, $unserialize = true);
}
namespace IlluminateEncryption;
use IlluminateContractsEncryptionEncrypter as EncrypterContract;
class Encrypter implements EncrypterContract
{
/**
* Create a new encrypter instance.
*/
public function __construct($key, $cipher = 'AES-128-CBC')
{
$this->key = (string) $key;
$this->cipher = $cipher;
}
/**
* Encrypt the given value.
*/
public function encrypt($value, $serialize = true)
{
// Do the encrypt part and return the encrypted value
}
/**
* Decrypt the given value.
*/
public function decrypt($payload, $unserialize = true)
{
// Do the decrypt part and return the original value
}
}
use IlluminateContractsEncryptionEncrypter as EncrypterContract;
class MD5Encrypter implements EncrypterContract
{
const ENCRYPTION_KEY = 'qJB0rGtIn5UB1xG03efyCp';
/**
* Encrypt the given value.
*/
public function encrypt($value, $serialize = true)
{
return base64_encode(mcrypt_encrypt(
MCRYPT_RIJNDAEL_256,
md5(self::ENCRYPTION_KEY),
$value,
MCRYPT_MODE_CBC,
md5(md5(self::ENCRYPTION_KEY))
));
}
/**
* Decrypt the given value.
*/
public function decrypt($payload, $unserialize = true)
{
return rtrim(mcrypt_decrypt(
MCRYPT_RIJNDAEL_256,
md5(self::ENCRYPTION_KEY),
base64_decode($payload),
MCRYPT_MODE_CBC,
md5(md5(self::ENCRYPTION_KEY))
), "0");
}
}
Laravel Strategy Pattern Examples
IlluminateContractsAuthGaurd
IlluminateContractsCacheStore
IlluminateContractsEncryptionEncrypter
IlluminateContractsEventsDispatcher
IlluminateContractsHashingHasher
IlluminateContractsLoggingLog
IlluminateContractsSessionSession
IlluminateContractsTranslationLoader
Provider Pattern
Provider Pattern
Sets a pattern for providing some
essential service
Provider Pattern Example
class DominosServiceProvider extends ServiceProvider
{
public function register()
{
// Register your services here
}
}
use AppDominosPizzaManager;
class PizzaServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('pizza-manager', function ($app) {
return new PizzaManager();
});
}
}
// Using instantiation
$pizzaManager = new AppDominosPizzaManager();
// Using the provider pattern and the container
$pizzaManager = app('pizza-manager');
$margaritha = $pizzaManager->driver('margaritha');
$chicken = $pizzaManager->driver('chicken-pizza');
Provider Pattern Laravel Example
class DebugbarServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton('debugbar', function ($app) {
$debugbar = new LaravelDebugbar($app);
if ($app->bound(SessionManager::class)) {
$sessionManager = $app->make(SessionManager::class);
$httpDriver = new SymfonyHttpDriver($sessionManager);
$debugbar->setHttpDriver($httpDriver);
}
return $debugbar;
});
}
}
Factory Pattern Recap
Factory translates interface to an instance
Builder Pattern Recap
Builder Pattern can do the configuration
for a new object without passing this
configuration to that object
Strategy Pattern Recap
Strategy pattern provides one place where
the correct strategy (algorithm) is called
Provider Pattern Recap
Provider Pattern let you extend the
framework by registering new classes in
the container
Wrapping up
Wrapping up
use AppDominosPizzaManager;
class PizzaServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('pizza-manager', function ($app) {
return new PizzaManager();
});
}
}
Design Pattern Fever
Want to learn more?
More Design Patterns: http://goo.gl/sHT3xK
Slideshare: https://goo.gl/U3YncS
Thank youBobby Bouwmann
@bobbybouwmann
Feedback: https://joind.in/talk/25af5
Thank youBobby Bouwmann
@bobbybouwmann
Feedback: https://joind.in/talk/25af5

More Related Content

What's hot

Domain Driven Design using Laravel
Domain Driven Design using LaravelDomain Driven Design using Laravel
Domain Driven Design using Laravelwajrcs
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101Adam Culp
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?FITC
 
c++ project on restaurant billing
c++ project on restaurant billing c++ project on restaurant billing
c++ project on restaurant billing Swakriti Rathore
 
Software Design Patterns in Laravel by Phill Sparks
Software Design Patterns in Laravel by Phill SparksSoftware Design Patterns in Laravel by Phill Sparks
Software Design Patterns in Laravel by Phill SparksPhill Sparks
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass SlidesNir Kaufman
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't FreeKelley Robinson
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented ProgrammingScott Wlaschin
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programmingScott Wlaschin
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in phpCPD INDIA
 
Konsep Routing dalam Laravel (Pemrograman Web II)
Konsep Routing dalam Laravel (Pemrograman Web II)Konsep Routing dalam Laravel (Pemrograman Web II)
Konsep Routing dalam Laravel (Pemrograman Web II)I Gede Iwan Sudipa
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix itRafael Dohms
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHPNisa Soomro
 

What's hot (20)

Domain Driven Design using Laravel
Domain Driven Design using LaravelDomain Driven Design using Laravel
Domain Driven Design using Laravel
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
c++ project on restaurant billing
c++ project on restaurant billing c++ project on restaurant billing
c++ project on restaurant billing
 
Software Design Patterns in Laravel by Phill Sparks
Software Design Patterns in Laravel by Phill SparksSoftware Design Patterns in Laravel by Phill Sparks
Software Design Patterns in Laravel by Phill Sparks
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
NestJS
NestJSNestJS
NestJS
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't Free
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Django forms
Django formsDjango forms
Django forms
 
Konsep Routing dalam Laravel (Pemrograman Web II)
Konsep Routing dalam Laravel (Pemrograman Web II)Konsep Routing dalam Laravel (Pemrograman Web II)
Konsep Routing dalam Laravel (Pemrograman Web II)
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Lesson 4 constant
Lesson 4  constantLesson 4  constant
Lesson 4 constant
 
Php functions
Php functionsPhp functions
Php functions
 

Similar to Laravel Design Patterns

Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UKKey Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UKMax Pronko
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmersAlexander Varwijk
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboardsDenis Ristic
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodeSWIFTotter Solutions
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injectionJosh Adell
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using CodeceptionJeroen van Dijk
 
Magento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request FlowMagento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request FlowVrann Tulika
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 
Oop php 5
Oop php 5Oop php 5
Oop php 5phpubl
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJames Casey
 
Getting the Most Out of jQuery Widgets
Getting the Most Out of jQuery WidgetsGetting the Most Out of jQuery Widgets
Getting the Most Out of jQuery Widgetsvelveeta_512
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐいHisateru Tanaka
 
Into the ZF2 Service Manager
Into the ZF2 Service ManagerInto the ZF2 Service Manager
Into the ZF2 Service ManagerChris Tankersley
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris Wallsmith
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperGary Hockin
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Djangofool2nd
 

Similar to Laravel Design Patterns (20)

Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UKKey Insights into Development Design Patterns for Magento 2 - Magento Live UK
Key Insights into Development Design Patterns for Magento 2 - Magento Live UK
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injection
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
Magento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request FlowMagento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request Flow
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
Oop php 5
Oop php 5Oop php 5
Oop php 5
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Django quickstart
Django quickstartDjango quickstart
Django quickstart
 
Getting the Most Out of jQuery Widgets
Getting the Most Out of jQuery WidgetsGetting the Most Out of jQuery Widgets
Getting the Most Out of jQuery Widgets
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Into the ZF2 Service Manager
Into the ZF2 Service ManagerInto the ZF2 Service Manager
Into the ZF2 Service Manager
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 

Recently uploaded

WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 

Recently uploaded (20)

WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 

Laravel Design Patterns

  • 2. About Me Bobby Bouwmann @bobbybouwmann Enrise -Code Cuisine markdownmail.com Laracasts
  • 3.
  • 6. What are Design Patterns?
  • 7. Design Patterns are ... Recipes for building maintainable code
  • 8. Be your own Chef Using the boundaries of Design Pattern
  • 9. Why use Design Patterns? — Provides a way to solve issues related to software development using a proven solution — Makes communication between developer more efficient
  • 10. Why use Design Patterns? — There is no"silver bullet"for using design pattern,each project and situation is different
  • 12. Maintainable Code — Understandable — Intuitive — Adaptable — Extendable — Debuggable
  • 13. Maintainable Code — Don't Repeat Yourself — Keep It Simple Stupid
  • 15. Design Pattern types — Creational Patterns — Structural Patterns — Behavioural Patterns
  • 16. Creational Patterns — Class instantiation — Hiding the creation logic — Examples: Factory,Builder,Prototype,Singleton
  • 17. Structural Patterns — Composition between objects — Usages of interfaces,abstract classes — Examples: Adapter,Bridge,Decorator,Facade,Proxy
  • 18. Behavioural Patterns — Communication between objects — Usages of mostly interfaces — Examples: Command,Iterator,Observer,State,Strategy
  • 19. Design Patterns in Laravel — Factory Pattern — Builder (Manager) Pattern — Strategy Pattern — Provider Pattern — Repository Pattern — Iterator Pattern — Singleton Pattern — Presenter Pattern
  • 20. Design Patterns in Laravel — Factory Pattern — Builder (Manager) Pattern — Strategy Pattern — Provider Pattern
  • 22.
  • 23.
  • 24.
  • 25.
  • 26. Factory Pattern Provides an interface for creating objects without specifying their concrete classes.
  • 27. Factory Pattern — Decouples code — Factory is responsible for creating objects,not the client — Multiple clients call the same factory,one place for changes — Easier to test,easy to mock and isolate
  • 28. Factory Pattern Example interface PizzaFactoryContract { public function make(array $toppings = []): Pizza; } class PizzaFactory implements PizzaFactoryContract { public function make(array $toppings = []): Pizza { return new Pizza($toppings); } } $pizza = (new PizzaFactory)->make(['chicken', 'onion']);
  • 29. Factory Pattern Laravel Example class PostsController { public function index(): IlluminateViewView { $posts = Post::all(); return view('posts.index', ['posts' => $posts]); } }
  • 30. // IlluminateFoundationhelpers.php /** * @return IlluminateViewView|IlluminateContractsViewFactory */ function view($view = null, $data = [], $mergeData = []) { $factory = app(ViewFactory::class); if (func_num_args() === 0) { return $factory; } return $factory->make($view, $data, $mergeData); }
  • 31. /** * Get the evaluated view contents for the given view. * * @return IlluminateContractsViewView */ public function make($view, $data = [], $mergeData = []) { $path = $this->finder->find( $view = $this->normalizeName($view) ); $data = array_merge($mergeData, $this->parseData($data)); return tap($this->viewInstance($view, $path, $data), function ($view) { $this->callCreator($view); }); } /** * Create a new view instance from the given arguments. * * @return IlluminateContractsViewView */ protected function viewInstance($view, $path, $data) { return new View($this, $this->getEngineFromPath($path), $view, $path, $data); }
  • 32. /** * Create a new Validator instance. * * @return IlluminateValidationValidator */ public function make(array $data, array $rules, array $messages = [], array $customAttributes = []) { $validator = $this->resolve( $data, $rules, $messages, $customAttributes ); $this->addExtensions($validator); return $validator; } /** * Resolve a new Validator instance. * * @return IlluminateValidationValidator */ protected function resolve(array $data, array $rules, array $messages, array $customAttributes) { if (is_null($this->resolver)) { return new Validator($this->translator, $data, $rules, $messages, $customAttributes); } return call_user_func($this->resolver, $this->translator, $data, $rules, $messages, $customAttributes); }
  • 34.
  • 35.
  • 36.
  • 37. Builder (Manager) Pattern Builds complex objects step by step.It can return different objects based on the given data.
  • 38. Builder (Manager) Pattern — Decouples code — Focuses on building complex objects step by step and returns them — Has functionality to decide which objects should be returned
  • 39. Builder Pattern Example class PizzaBuilder { public function make(PizzaBuilderInterface $pizza): Pizza { // Returns object of type Pizza } }
  • 40. class PizzaBuilder { public function make(PizzaBuilderInterface $pizza): Pizza { $pizza->prepare(); $pizza->applyToppings(); $pizza->bake(); return $pizza; } }
  • 41. interface PizzaBuilderInterface { public function prepare(): Pizza; public function applyToppings(): Pizza; public function bake(): Pizza; }
  • 42. class MargarithaBuilder implements PizzaBuilderInterface { protected $pizza; public function prepare(): Pizza { $this->pizza = new Pizza(); return $this->pizza; } public function applyToppings(): Pizza { $this->pizza->setToppings(['cheese', 'tomato']); return $this->pizza; } public function bake(): Pizza { $this->pizza->setBakingTemperature(180); $this->pizza->setBakingMinutes(8); return $this->pizza; } }
  • 43. class PizzaBuilder { public function make(PizzaBuilderInterface $pizza): Pizza { return $pizza ->prepare(); ->applyToppings(); ->bake(); } } // Create a PizzaBuilder $pizzaBuilder = new PizzaBuilder; // Create pizza using Builder which returns Pizza instance $pizza = $pizzaBuilder->make(new MargarithaBuilder());
  • 44. class ChickenBuilder implements PizzaBuilderInterface { protected $pizza; public function prepare(): Pizza { $this->pizza = new Pizza(); return $this->pizza; } public function applyToppings(): Pizza { $this->pizza->setToppings(['cheese', 'tomato', 'chicken', 'corn']); return $this->pizza; } public function bake(): Pizza { $this->pizza->setBakingTemperature(200) $this->pizza->setBakingMinutes(8); return $this->pizza; } }
  • 45. class PizzaBuilder { public function make(PizzaBuilderInterface $pizza): Pizza { return $pizza ->prepare() ->applyToppings() ->bake(); } } $pizzaBuilder = new PizzaBuilder; $pizzaOne = $pizzaBuilder->make(new MargarithaBuilder()); $pizzaTwo = $pizzaBuilder->make(new ChickenBuilder());
  • 47. class PizzaManager extends IlluminateSupportManager { public function getDefaultDriver() { return 'margaritha'; } public function createMargarithaDriver(): PizzaBuilderInterface { return new MargarithaBuilder(); } public function createChickenPizzaDriver(): PizzaBuilderInterface { return new ChickenPizzaBuilder(); } }
  • 48. public function driver($driver = null) { $driver = $driver ?: $this->getDefaultDriver(); // If the given driver has not been created before, we will create the instances // here and cache it so we can return it next time very quickly. If there is // already a driver created by this name, we'll just return that instance. if (! isset($this->drivers[$driver])) { $this->drivers[$driver] = $this->createDriver($driver); } return $this->drivers[$driver]; }
  • 49. protected function createDriver($driver) { // We'll check to see if a creator method exists for the given driver. If not we // will check for a custom driver creator, which allows developers to create // drivers using their own customized driver creator Closure to create it. if (isset($this->customCreators[$driver])) { return $this->callCustomCreator($driver); } else { $method = 'create' . Str::studly($driver) . 'Driver'; if (method_exists($this, $method)) { return $this->$method(); } } throw new InvalidArgumentException("Driver [$driver] not supported."); }
  • 50. class PizzaManager extends IlluminateSupportManager { public function getDefaultDriver() { return 'margaritha'; } public function createMargarithaDriver(): PizzaBuilderInterface { return new MargarithaBuilder(); } } $manager = new PizzaManager(); // MargarithaBuilder implementing PizzaBuilderInterface $builder = $manager->driver('margaritha'); $pizza = $builder->make(); // Pizza
  • 51. // IlluminateMailTransportManager class TransportManager extends Manager { protected function createSmtpDriver() { // Code for building up a SmtpTransport class } protected function createMailgunDriver() { // Code for building up a MailgunTransport class } protected function createSparkpostDriver() { // Code for building up a SparkpostTransport class } protected function createLogDriver() { // Code for building up a LogTransport class } }
  • 52. class TransportManager extends Manager { public function getDefaultDriver() { return $this->app['config']['mail.driver']; } // All create{$driver}Driver methods }
  • 53. // config/mail.php 'driver' => env('MAIL_DRIVER', 'smtp'),
  • 54. // config/mail.php 'driver' => env('MAIL_DRIVER', 'smtp'), // IlluminateMailTransportManager createSmtpDriver()
  • 55. // config/mail.php 'driver' => env('MAIL_DRIVER', 'smtp'), // IlluminateMailTransportManager createSmtpDriver() // app/Http/Controllers/RegisterController Mail::to($user) ->send(new UserRegistered($user));
  • 56. Laravel Manager Pattern Examples IlluminateAuthAuthManager IlluminateBroadcastingBroadcastManager IlluminateCacheCacheManager IlluminateFilesystemFilesystemManager IlluminateMailTransportManager IlluminateNotificationsChannelManager IlluminateQueueQueueManager IlluminateSessionSessionManager
  • 58.
  • 59.
  • 60.
  • 61.
  • 62. Strategy Pattern Defines a familiy of algorithms that are interchangeable
  • 63. Strategy Pattern Program to an interface, not an implementation.
  • 64. Strategy Pattern Example interface DeliveryStrategy { public function deliver(Address $address); }
  • 65. interface DeliveryStrategy { public function deliver(Address $address); } class BikeDelivery implements DeliveryStrategy { public function deliver(Address $address): { $route = new BikeRoute($address); echo $route->calculateCosts(); echo $route->calculateDeliveryTime(); } }
  • 66. class PizzaDelivery { public function deliverPizza(DeliveryStrategy $strategy, Address $address) { return $strategy->deliver($address); } } $address = new Address('Meer en Vaart 300, Amsterdam'); $delivery = new PizzaDelivery(); $delivery->deliver(new BikeDelivery(), $address);
  • 67. class DroneDelivery implements DeliveryStrategy { public function deliver(Address $address): { $route = new DroneRoute($address); echo $route->calculateCosts(); echo $route->calculateFlyTime(); } }
  • 68. class PizzaDelivery { public function deliverPizza(DeliveryStrategy $strategy, Address $address) { return $strategy->deliver($address); } } $address = new Address('Meer en Vaart 300, Amsterdam'); $delivery = new PizzaDelivery(); $delivery->deliver(new BikeDelivery(), $address); $delivery->deliver(new DroneDelivery(), $address);
  • 70. <?php namespace IlluminateContractsEncryption; interface Encrypter { /** * Encrypt the given value. * * @param string $value * @param bool $serialize * @return string */ public function encrypt($value, $serialize = true); /** * Decrypt the given value. * * @param string $payload * @param bool $unserialize * @return string */ public function decrypt($payload, $unserialize = true); }
  • 71. namespace IlluminateEncryption; use IlluminateContractsEncryptionEncrypter as EncrypterContract; class Encrypter implements EncrypterContract { /** * Create a new encrypter instance. */ public function __construct($key, $cipher = 'AES-128-CBC') { $this->key = (string) $key; $this->cipher = $cipher; } /** * Encrypt the given value. */ public function encrypt($value, $serialize = true) { // Do the encrypt part and return the encrypted value } /** * Decrypt the given value. */ public function decrypt($payload, $unserialize = true) { // Do the decrypt part and return the original value } }
  • 72. use IlluminateContractsEncryptionEncrypter as EncrypterContract; class MD5Encrypter implements EncrypterContract { const ENCRYPTION_KEY = 'qJB0rGtIn5UB1xG03efyCp'; /** * Encrypt the given value. */ public function encrypt($value, $serialize = true) { return base64_encode(mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5(self::ENCRYPTION_KEY), $value, MCRYPT_MODE_CBC, md5(md5(self::ENCRYPTION_KEY)) )); } /** * Decrypt the given value. */ public function decrypt($payload, $unserialize = true) { return rtrim(mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5(self::ENCRYPTION_KEY), base64_decode($payload), MCRYPT_MODE_CBC, md5(md5(self::ENCRYPTION_KEY)) ), "0"); } }
  • 73. Laravel Strategy Pattern Examples IlluminateContractsAuthGaurd IlluminateContractsCacheStore IlluminateContractsEncryptionEncrypter IlluminateContractsEventsDispatcher IlluminateContractsHashingHasher IlluminateContractsLoggingLog IlluminateContractsSessionSession IlluminateContractsTranslationLoader
  • 75.
  • 76.
  • 77. Provider Pattern Sets a pattern for providing some essential service
  • 78. Provider Pattern Example class DominosServiceProvider extends ServiceProvider { public function register() { // Register your services here } }
  • 79. use AppDominosPizzaManager; class PizzaServiceProvider extends ServiceProvider { public function register() { $this->app->bind('pizza-manager', function ($app) { return new PizzaManager(); }); } }
  • 80. // Using instantiation $pizzaManager = new AppDominosPizzaManager(); // Using the provider pattern and the container $pizzaManager = app('pizza-manager'); $margaritha = $pizzaManager->driver('margaritha'); $chicken = $pizzaManager->driver('chicken-pizza');
  • 82. class DebugbarServiceProvider extends ServiceProvider { public function register() { $this->app->singleton('debugbar', function ($app) { $debugbar = new LaravelDebugbar($app); if ($app->bound(SessionManager::class)) { $sessionManager = $app->make(SessionManager::class); $httpDriver = new SymfonyHttpDriver($sessionManager); $debugbar->setHttpDriver($httpDriver); } return $debugbar; }); } }
  • 83. Factory Pattern Recap Factory translates interface to an instance
  • 84. Builder Pattern Recap Builder Pattern can do the configuration for a new object without passing this configuration to that object
  • 85. Strategy Pattern Recap Strategy pattern provides one place where the correct strategy (algorithm) is called
  • 86. Provider Pattern Recap Provider Pattern let you extend the framework by registering new classes in the container
  • 88. Wrapping up use AppDominosPizzaManager; class PizzaServiceProvider extends ServiceProvider { public function register() { $this->app->bind('pizza-manager', function ($app) { return new PizzaManager(); }); } }
  • 90. Want to learn more? More Design Patterns: http://goo.gl/sHT3xK Slideshare: https://goo.gl/U3YncS