SlideShare una empresa de Scribd logo
1 de 36
Descargar para leer sin conexión
RichModel
And Layered Architecture
        Kirill chEbba Chebunin
                (Creara.ru)
            iam@chebba.org
Rich Model. ???




                  http://www.vexinthecity.com/2010/10/estee-lauder-christmas-collection-pure.html




                                                  © Kirill chEbba Chebunin. Creara 2012
Rich Model. Who?


    Martin Fowler
      –   Anemic Domain Model
      –   Domain Model
      –   Transaction Script

    Eric Evans
      –   Domain-Driven Design

    Benjamin Eberlei
      –   Building an Object Model: No setters allowed




                                                         © Kirill chEbba Chebunin. Creara 2012
Rich Model. What?


    About business objects – Entities

    Data + Logic instead of pure Data (Anemic Model)

    Real encapsulation

    Consistent state

    Business methods instead of Setters

    Low level validation




                                            © Kirill chEbba Chebunin. Creara 2012
Rich Model. How?
class Project
{
    const STATUS_NEW     = 'new';
    const STATUS_ACTIVE = 'active';
    const STATUS_BLOCKED = 'blocked';

    private $name;
    private $status;

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setStatus($status)
    {
        $this->status = $status;
    }

    public function getStatus()
    {
        return $this->status;
    }
}




                                         © Kirill chEbba Chebunin. Creara 2012
Rich Model. How?
class Project                                   http://rober-raik.deviantart.com/art/Fuck-You-263589802
{
    const STATUS_NEW     = 'new';
    const STATUS_ACTIVE = 'active';
    const STATUS_BLOCKED = 'blocked';

    private $name;
    private $status;

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setStatus($status)
    {
        $this->status = $status;
    }

    public function getStatus()
    {
        return $this->status;
    }
}

                                         FUCK YOU, SETTERS!

                                                 © Kirill chEbba Chebunin. Creara 2012
Rich Model. How?
class Project                            class Project
{                                        {
    const STATUS_NEW     = 'new';            const STATUS_NEW     = 'new';
    const STATUS_ACTIVE = 'active';          const STATUS_ACTIVE = 'active';
    const STATUS_BLOCKED = 'blocked';        const STATUS_BLOCKED = 'blocked';

    private $name;                           private $name;
    private $status;                         private $status;

    public function setName($name)           public function __construct($name)
    {                                        {
        $this->name = $name;                     $this->name = trim($name);
    }                                            $this->status = self::STATUS_NEW;
                                             }
    public function getName()
    {                                        public function getName()
        return $this->name;                  {
    }                                            return $this->name;
                                             }
    public function setStatus($status)
    {                                        public function getStatus()
        $this->status = $status;             {
    }                                            return $this->status;
                                             }
    public function getStatus()
    {                                        public function activate()
        return $this->status;                {
    }                                            if ($this->status === self::STATUS_BLOCKED) {
}                                                    throw new LogicException(
                                                         'Can not activate blocked project');
                                                 }

                                                 $this->status = self::STATUS_ACTIVE;
                                             }
                                         }

                                                                  © Kirill chEbba Chebunin. Creara 2012
rd
Rich Model. 3 Party?




                       © Kirill chEbba Chebunin. Creara 2012
rd
Rich Model. 3 Party?


    Doctrine2
      – Persistence Layer
      – Same as Serialization

    Symfony2 Form
      – Data Binder
      – Born to use Accessors
      – Data Transformers?

    Symfony2 Validation
      – External Validation
      – Heavyweight for Internal Validation




                                              © Kirill chEbba Chebunin. Creara 2012
Rich Model. Doctrine Side Effects
   $entity = $this->em->find($className, $id);
   try {
       $this->update($entity, $data);
       // Failed, no update was executed
   } catch (ValidationException $e) {
       // Do stuff on fail
   }

   // .................................

   $entity->link($anotherEntity);
   $this->em->flush();
   // Old invalid updates will be executed




                                          © Kirill chEbba Chebunin. Creara 2012
rd
Rich Model. 3 Party?




                       © Kirill chEbba Chebunin. Creara 2012
Rich Model. Solution.


    Isolated Persistence Layer

    Transactional Operations

    Rich + Anemic Objects (DTO)

    Service Layer (Facade)




                                  © Kirill chEbba Chebunin. Creara 2012
Rich Model. DTO.
class ProjectData
{
    /**
     * @AssertNotBlank
     * @AssertRegex(pattern="/[a-z0-9_]+/i")
     */
    private $name;

    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    public function getName()
    {
        return $this->name;
    }
}




                                                © Kirill chEbba Chebunin. Creara 2012
Rich Model. Domain Interface.
interface   Project
{
    const   STATUS_NEW     = 'new';
    const   STATUS_ACTIVE = 'active';
    const   STATUS_BLOCKED = 'blocked';

    /**
     * Get project name
     *
     * @return string
     */
    public function getName();

    /**
     * Get project status
     *
     * @return string STATUS_* constant
     */
    public function getStatus();
}

                                          © Kirill chEbba Chebunin. Creara 2012
Rich Model. Service Layer.
interface ProjectService
{
    /**
     * Create new project
     *
     * @param ProjectData $data
     *
     * @return Project
     * @throws ValidationException
     */
    public function createProject(ProjectData $data);
}




                                             © Kirill chEbba Chebunin. Creara 2012
Rich Model. Example.
class ProjectManager implements ProjectService
{
    /* ... */


    public function createProject(ProjectData $data)
    {
        $this->validate($data);
        $project = new EntityProject($data->getName());
        $this->em->persist($project);
        $this->em->flush();


        return $project;
    }
}


                                             © Kirill chEbba Chebunin. Creara 2012
Rich Model. Example.
class ProjectController extends Controller
{
    public function createAction(Request $request)
    {
        $data = new ProjectData();
        $form = $this->createForm(new ProjectType(), $data);
        $form->bind($request);
        if ($form->isValid()) {
            return
               $this->projectService->createProject($data);
        }
        return $form;
    }
}


                                             © Kirill chEbba Chebunin. Creara 2012
Rich Model. Solution.

                   Client Code
            Controller, Command, etc.

             DTO


                                        Domain
                                       Interface

                   Service Interface

                   Persistence Layer


                                         © Kirill chEbba Chebunin. Creara 2012
Rich Model. Profit?




                      © Kirill chEbba Chebunin. Creara 2012
Rich Model. Profit?




                      © Kirill chEbba Chebunin. Creara 2012
rd
Rich Model. 3 Party Bundles.





    Anemic Model

    Managers

    Direct ObjectManager Manipulation




                                        © Kirill chEbba Chebunin. Creara 2012
Rich Model. FOSUser.




                       © Kirill chEbba Chebunin. Creara 2012
Rich Model. FOSUser. Problems.


    User
      – Property Setters
      – Unnecessary Functions

    Manager
      – Low Level Methods




                                 © Kirill chEbba Chebunin. Creara 2012
Rich Model. FOSUser. Solution.

Delegation                                                        instead of               Inheritance




http://thevanwinkleproject.blogspot.com/2011_02_01_archive.html                http://www.halloweencostumes.com/sweet-daddy-pimp-costume.html




                                                                                                 © Kirill chEbba Chebunin. Creara 2012
Rich Model. FOSUser. Delegation.
class UserWrapper implements FOSUserInterface
{
    private $user;
    private $email;
    private $enabled = false;

    public function __construct(DomainUser $user = null)
    {
        if ($user) {
            $this->setUser($user);
        }
    }

    public function setUser(DomainUser $user)
    {
        $this->user = $user;
        $this
            ->setEmail($user->getEmail())
            ->setEnabled($user->getStatus() == DomainUser::STATUS_ACTIVE)
        ;
    }

    // Other UserInterface methods
}


                                                     © Kirill chEbba Chebunin. Creara 2012
Rich Model. FOSUser. Delegation.
class FOSUserManager implements FOSUserManagerInterface
{
    public function updateUser(UserInterface $wrapper)
    {
        $user = $wrapper->getUser();
        $userService = $this->userService;

        // User registration
        if (!$user) {
            $user = $userService->registerUser($wrapper->getRegistrationData());
        // Update simple fields
        } else {
            $user = $userService->updateUser($id, $wrapper->getUserData());
        }

        $wrapper->setUser($user);
    }

    // Other UserManagerInterface methods
}




                                                          © Kirill chEbba Chebunin. Creara 2012
Rich Model. SonataAdmin.




http://southpark.wikia.com/wiki/File:ScauseForApplause00031.png




                                                                  © Kirill chEbba Chebunin. Creara 2012
Rich Model. Admin Architecture.


    SonataAdminBundle
      – Base CRUD View Functions
      – Dashboard, Menu, etc.
      – Interfaces for Storage Implementations

    ORM/ODM/... Bundles
      – Storage Implementations registered in Admin
      – Direct Object Manager Manipulation




                                                      © Kirill chEbba Chebunin. Creara 2012
Rich Model. Admin Interfaces.

We have interfaces! Implement them!
class CustomModelManager implements ModelManagerInterface
{
    /* ... */

    /**
      * {@inheritDoc}
      */
    public function modelTransform($class, $instance)
    {
         // Method is not used in Admin
    }

    /**
      * {@inheritDoc}
      */
    public function getParentFieldDescription($parentAssociationMapping, $class)
    {
         // Method is not used in Admin
    }
}




                                                            © Kirill chEbba Chebunin. Creara 2012
Rich Model. Admin Interfaces.




                                © Kirill chEbba Chebunin. Creara 2012
Rich Model. Admin.Custom Model.
interface Model
{
    /**
     * Create mew object instance
     *
     * @return mixed
     */
    public function createInstance();

    /**
     * Save new object
     *
     * @param object $object
     *
     * @throws RuntimeException
    */
    public function create($object);

    /**
     * Update existing object
     *
     * @param $object
     * @throws RuntimeException
    */
    public function update($object);

    // Some other methods
}

                                        © Kirill chEbba Chebunin. Creara 2012
Rich Model. Admin.Custom Model.
class UserModel implements Model
{

    public function createInstance()
    {
        return new UserWrapper();
    }

    public function create($wrapper)
    {
        $user = $this->userService->registerUser(
            $wrapper->getRegistrationData()
        );
        $wrapper->setUser($user);
    }

    public function update($wrapper)
    {
        $user = $this->userService->updateUser(
            $wrapper->getUserData()
        );
        $wrapper->setUser($user);
    }

    // Some other methods
}



                                                    © Kirill chEbba Chebunin. Creara 2012
Rich Model. PROFIT!




                      © Kirill chEbba Chebunin. Creara 2012
Rich Model. Summary.


    Object Logic in Object Class

    Separate Domain Objects from View Object

    Isolated Business Layer (Service Layer)

    Delegation instead of Inheritance

    Read 3rd Party Code




                                              © Kirill chEbba Chebunin. Creara 2012
Rich Model. Pros & Cons.


    OOPed (KISS, DRY, Patterns, blah, blah, blah)

    Pros:
      – Less side effects
      – Less code duplication
      – Less chances to shoot your leg
      – Easy serialization
      – Easy API creation
      – Etc, etc, etc.

    Cons:
      – More code
      – Codebase required
      – Hi shit sort out level


                                            © Kirill chEbba Chebunin. Creara 2012
Rich Model. Questions?




                         © Kirill chEbba Chebunin. Creara 2012

Más contenido relacionado

La actualidad más candente

Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Kacper Gunia
 
Symfony without the framework
Symfony without the frameworkSymfony without the framework
Symfony without the frameworkGOG.com dev team
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteLeonardo Proietti
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersKacper Gunia
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2Kacper Gunia
 
Dependency Injection in PHP
Dependency Injection in PHPDependency Injection in PHP
Dependency Injection in PHPKacper Gunia
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Konstantin Kudryashov
 
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupScaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupKacper Gunia
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mockingKonstantin Kudryashov
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)New Symfony Tips & Tricks (SymfonyCon Paris 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)Javier Eguiluz
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Fabien Potencier
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful softwareJorn Oomen
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5 Wildan Maulana
 
Decoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDDecoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDAleix Vergés
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf Conference
 

La actualidad más candente (20)

Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
 
Symfony without the framework
Symfony without the frameworkSymfony without the framework
Symfony without the framework
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4Developers
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2
 
Dependency Injection in PHP
Dependency Injection in PHPDependency Injection in PHP
Dependency Injection in PHP
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupScaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Zero to SOLID
Zero to SOLIDZero to SOLID
Zero to SOLID
 
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)New Symfony Tips & Tricks (SymfonyCon Paris 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
 
Decoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDDecoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDD
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
 

Destacado

Application Layer in PHP
Application Layer in PHPApplication Layer in PHP
Application Layer in PHPPer Bernhardt
 
A Layered Architecture for the Model-driven Development of Distributed Simula...
A Layered Architecture for the Model-driven Development of Distributed Simula...A Layered Architecture for the Model-driven Development of Distributed Simula...
A Layered Architecture for the Model-driven Development of Distributed Simula...Daniele Gianni
 
Bug deBug Chennai 2012 Talk - Test automation support systems layered archite...
Bug deBug Chennai 2012 Talk - Test automation support systems layered archite...Bug deBug Chennai 2012 Talk - Test automation support systems layered archite...
Bug deBug Chennai 2012 Talk - Test automation support systems layered archite...RIA RUI Society
 
Agile Entwicklung OXID Commons
Agile Entwicklung OXID CommonsAgile Entwicklung OXID Commons
Agile Entwicklung OXID CommonsLars Jankowfsky
 
Introduction to architectural patterns
Introduction to architectural patternsIntroduction to architectural patterns
Introduction to architectural patternsGeorgy Podsvetov
 
Hexagonal architecture - message-oriented software design (PHP Benelux 2016)
Hexagonal architecture - message-oriented software design (PHP Benelux 2016)Hexagonal architecture - message-oriented software design (PHP Benelux 2016)
Hexagonal architecture - message-oriented software design (PHP Benelux 2016)Matthias Noback
 
Layered Architecture 03 Format
Layered Architecture 03 FormatLayered Architecture 03 Format
Layered Architecture 03 Formatanishgoel
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
 
Soa Overview
Soa OverviewSoa Overview
Soa OverviewTerry Cho
 
CQRS на практике. В поиске точки масштабирования и новых метафор
CQRS на практике. В поиске точки масштабирования и новых метафорCQRS на практике. В поиске точки масштабирования и новых метафор
CQRS на практике. В поиске точки масштабирования и новых метафорAlexander Byndyu
 
Why Architecture in Web Development matters
Why Architecture in Web Development mattersWhy Architecture in Web Development matters
Why Architecture in Web Development mattersLars Jankowfsky
 
N-Tier, Layered Design, SOA
N-Tier, Layered Design, SOAN-Tier, Layered Design, SOA
N-Tier, Layered Design, SOASperasoft
 
Software engineering : Layered Architecture
Software engineering : Layered ArchitectureSoftware engineering : Layered Architecture
Software engineering : Layered ArchitectureMuhammed Afsal Villan
 
Software Engineering - Ch11
Software Engineering - Ch11Software Engineering - Ch11
Software Engineering - Ch11Siddharth Ayer
 
Software Architecture Patterns
Software Architecture PatternsSoftware Architecture Patterns
Software Architecture PatternsAssaf Gannon
 
Layered architecture style
Layered architecture styleLayered architecture style
Layered architecture styleBegench Suhanov
 
Implementing DDD Concepts in PHP
Implementing DDD Concepts in PHPImplementing DDD Concepts in PHP
Implementing DDD Concepts in PHPSteve Rhoades
 

Destacado (20)

Application Layer in PHP
Application Layer in PHPApplication Layer in PHP
Application Layer in PHP
 
A Layered Architecture for the Model-driven Development of Distributed Simula...
A Layered Architecture for the Model-driven Development of Distributed Simula...A Layered Architecture for the Model-driven Development of Distributed Simula...
A Layered Architecture for the Model-driven Development of Distributed Simula...
 
Bug deBug Chennai 2012 Talk - Test automation support systems layered archite...
Bug deBug Chennai 2012 Talk - Test automation support systems layered archite...Bug deBug Chennai 2012 Talk - Test automation support systems layered archite...
Bug deBug Chennai 2012 Talk - Test automation support systems layered archite...
 
Agile Entwicklung OXID Commons
Agile Entwicklung OXID CommonsAgile Entwicklung OXID Commons
Agile Entwicklung OXID Commons
 
Introduction to architectural patterns
Introduction to architectural patternsIntroduction to architectural patterns
Introduction to architectural patterns
 
Hexagonal architecture - message-oriented software design (PHP Benelux 2016)
Hexagonal architecture - message-oriented software design (PHP Benelux 2016)Hexagonal architecture - message-oriented software design (PHP Benelux 2016)
Hexagonal architecture - message-oriented software design (PHP Benelux 2016)
 
Layered Architecture 03 Format
Layered Architecture 03 FormatLayered Architecture 03 Format
Layered Architecture 03 Format
 
CQRS
CQRSCQRS
CQRS
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
Soa Overview
Soa OverviewSoa Overview
Soa Overview
 
Osi Model
Osi ModelOsi Model
Osi Model
 
CQRS на практике. В поиске точки масштабирования и новых метафор
CQRS на практике. В поиске точки масштабирования и новых метафорCQRS на практике. В поиске точки масштабирования и новых метафор
CQRS на практике. В поиске точки масштабирования и новых метафор
 
Why Architecture in Web Development matters
Why Architecture in Web Development mattersWhy Architecture in Web Development matters
Why Architecture in Web Development matters
 
N-Tier, Layered Design, SOA
N-Tier, Layered Design, SOAN-Tier, Layered Design, SOA
N-Tier, Layered Design, SOA
 
Software engineering : Layered Architecture
Software engineering : Layered ArchitectureSoftware engineering : Layered Architecture
Software engineering : Layered Architecture
 
Software Engineering - Ch11
Software Engineering - Ch11Software Engineering - Ch11
Software Engineering - Ch11
 
Software Architecture Patterns
Software Architecture PatternsSoftware Architecture Patterns
Software Architecture Patterns
 
Layered architecture style
Layered architecture styleLayered architecture style
Layered architecture style
 
Implementing DDD Concepts in PHP
Implementing DDD Concepts in PHPImplementing DDD Concepts in PHP
Implementing DDD Concepts in PHP
 
Ch6 architectural design
Ch6 architectural designCh6 architectural design
Ch6 architectural design
 

Similar a Rich Model And Layered Architecture in SF2 Application

How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris Wallsmith
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injectionJosh Adell
 
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
 
Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Rafael Dohms
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionRifat Nabi
 
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Ryan Mauger
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperJonathan Wage
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)Krzysztof Menżyk
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonfRafael Dohms
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Yevhen Kotelnytskyi
 
PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)Win Yu
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPmtoppa
 
A resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangleA resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangleAkihito Koriyama
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonKris Wallsmith
 
Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)Arnaud Langlade
 

Similar a Rich Model And Layered Architecture in SF2 Application (20)

How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injection
 
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
 
Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
 
PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHP
 
A resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangleA resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangle
 
SOLID PRINCIPLES
SOLID PRINCIPLESSOLID PRINCIPLES
SOLID PRINCIPLES
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
 
Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 

Último (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Rich Model And Layered Architecture in SF2 Application

  • 1. RichModel And Layered Architecture Kirill chEbba Chebunin (Creara.ru) iam@chebba.org
  • 2. Rich Model. ??? http://www.vexinthecity.com/2010/10/estee-lauder-christmas-collection-pure.html © Kirill chEbba Chebunin. Creara 2012
  • 3. Rich Model. Who?  Martin Fowler – Anemic Domain Model – Domain Model – Transaction Script  Eric Evans – Domain-Driven Design  Benjamin Eberlei – Building an Object Model: No setters allowed © Kirill chEbba Chebunin. Creara 2012
  • 4. Rich Model. What?  About business objects – Entities  Data + Logic instead of pure Data (Anemic Model)  Real encapsulation  Consistent state  Business methods instead of Setters  Low level validation © Kirill chEbba Chebunin. Creara 2012
  • 5. Rich Model. How? class Project { const STATUS_NEW = 'new'; const STATUS_ACTIVE = 'active'; const STATUS_BLOCKED = 'blocked'; private $name; private $status; public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } public function setStatus($status) { $this->status = $status; } public function getStatus() { return $this->status; } } © Kirill chEbba Chebunin. Creara 2012
  • 6. Rich Model. How? class Project http://rober-raik.deviantart.com/art/Fuck-You-263589802 { const STATUS_NEW = 'new'; const STATUS_ACTIVE = 'active'; const STATUS_BLOCKED = 'blocked'; private $name; private $status; public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } public function setStatus($status) { $this->status = $status; } public function getStatus() { return $this->status; } } FUCK YOU, SETTERS! © Kirill chEbba Chebunin. Creara 2012
  • 7. Rich Model. How? class Project class Project { { const STATUS_NEW = 'new'; const STATUS_NEW = 'new'; const STATUS_ACTIVE = 'active'; const STATUS_ACTIVE = 'active'; const STATUS_BLOCKED = 'blocked'; const STATUS_BLOCKED = 'blocked'; private $name; private $name; private $status; private $status; public function setName($name) public function __construct($name) { { $this->name = $name; $this->name = trim($name); } $this->status = self::STATUS_NEW; } public function getName() { public function getName() return $this->name; { } return $this->name; } public function setStatus($status) { public function getStatus() $this->status = $status; { } return $this->status; } public function getStatus() { public function activate() return $this->status; { } if ($this->status === self::STATUS_BLOCKED) { } throw new LogicException( 'Can not activate blocked project'); } $this->status = self::STATUS_ACTIVE; } } © Kirill chEbba Chebunin. Creara 2012
  • 8. rd Rich Model. 3 Party? © Kirill chEbba Chebunin. Creara 2012
  • 9. rd Rich Model. 3 Party?  Doctrine2 – Persistence Layer – Same as Serialization  Symfony2 Form – Data Binder – Born to use Accessors – Data Transformers?  Symfony2 Validation – External Validation – Heavyweight for Internal Validation © Kirill chEbba Chebunin. Creara 2012
  • 10. Rich Model. Doctrine Side Effects $entity = $this->em->find($className, $id); try { $this->update($entity, $data); // Failed, no update was executed } catch (ValidationException $e) { // Do stuff on fail } // ................................. $entity->link($anotherEntity); $this->em->flush(); // Old invalid updates will be executed © Kirill chEbba Chebunin. Creara 2012
  • 11. rd Rich Model. 3 Party? © Kirill chEbba Chebunin. Creara 2012
  • 12. Rich Model. Solution.  Isolated Persistence Layer  Transactional Operations  Rich + Anemic Objects (DTO)  Service Layer (Facade) © Kirill chEbba Chebunin. Creara 2012
  • 13. Rich Model. DTO. class ProjectData { /** * @AssertNotBlank * @AssertRegex(pattern="/[a-z0-9_]+/i") */ private $name; public function setName($name) { $this->name = $name; return $this; } public function getName() { return $this->name; } } © Kirill chEbba Chebunin. Creara 2012
  • 14. Rich Model. Domain Interface. interface Project { const STATUS_NEW = 'new'; const STATUS_ACTIVE = 'active'; const STATUS_BLOCKED = 'blocked'; /** * Get project name * * @return string */ public function getName(); /** * Get project status * * @return string STATUS_* constant */ public function getStatus(); } © Kirill chEbba Chebunin. Creara 2012
  • 15. Rich Model. Service Layer. interface ProjectService { /** * Create new project * * @param ProjectData $data * * @return Project * @throws ValidationException */ public function createProject(ProjectData $data); } © Kirill chEbba Chebunin. Creara 2012
  • 16. Rich Model. Example. class ProjectManager implements ProjectService { /* ... */ public function createProject(ProjectData $data) { $this->validate($data); $project = new EntityProject($data->getName()); $this->em->persist($project); $this->em->flush(); return $project; } } © Kirill chEbba Chebunin. Creara 2012
  • 17. Rich Model. Example. class ProjectController extends Controller { public function createAction(Request $request) { $data = new ProjectData(); $form = $this->createForm(new ProjectType(), $data); $form->bind($request); if ($form->isValid()) { return $this->projectService->createProject($data); } return $form; } } © Kirill chEbba Chebunin. Creara 2012
  • 18. Rich Model. Solution. Client Code Controller, Command, etc. DTO Domain Interface Service Interface Persistence Layer © Kirill chEbba Chebunin. Creara 2012
  • 19. Rich Model. Profit? © Kirill chEbba Chebunin. Creara 2012
  • 20. Rich Model. Profit? © Kirill chEbba Chebunin. Creara 2012
  • 21. rd Rich Model. 3 Party Bundles.  Anemic Model  Managers  Direct ObjectManager Manipulation © Kirill chEbba Chebunin. Creara 2012
  • 22. Rich Model. FOSUser. © Kirill chEbba Chebunin. Creara 2012
  • 23. Rich Model. FOSUser. Problems.  User – Property Setters – Unnecessary Functions  Manager – Low Level Methods © Kirill chEbba Chebunin. Creara 2012
  • 24. Rich Model. FOSUser. Solution. Delegation instead of Inheritance http://thevanwinkleproject.blogspot.com/2011_02_01_archive.html http://www.halloweencostumes.com/sweet-daddy-pimp-costume.html © Kirill chEbba Chebunin. Creara 2012
  • 25. Rich Model. FOSUser. Delegation. class UserWrapper implements FOSUserInterface { private $user; private $email; private $enabled = false; public function __construct(DomainUser $user = null) { if ($user) { $this->setUser($user); } } public function setUser(DomainUser $user) { $this->user = $user; $this ->setEmail($user->getEmail()) ->setEnabled($user->getStatus() == DomainUser::STATUS_ACTIVE) ; } // Other UserInterface methods } © Kirill chEbba Chebunin. Creara 2012
  • 26. Rich Model. FOSUser. Delegation. class FOSUserManager implements FOSUserManagerInterface { public function updateUser(UserInterface $wrapper) { $user = $wrapper->getUser(); $userService = $this->userService; // User registration if (!$user) { $user = $userService->registerUser($wrapper->getRegistrationData()); // Update simple fields } else { $user = $userService->updateUser($id, $wrapper->getUserData()); } $wrapper->setUser($user); } // Other UserManagerInterface methods } © Kirill chEbba Chebunin. Creara 2012
  • 28. Rich Model. Admin Architecture.  SonataAdminBundle – Base CRUD View Functions – Dashboard, Menu, etc. – Interfaces for Storage Implementations  ORM/ODM/... Bundles – Storage Implementations registered in Admin – Direct Object Manager Manipulation © Kirill chEbba Chebunin. Creara 2012
  • 29. Rich Model. Admin Interfaces. We have interfaces! Implement them! class CustomModelManager implements ModelManagerInterface { /* ... */ /** * {@inheritDoc} */ public function modelTransform($class, $instance) { // Method is not used in Admin } /** * {@inheritDoc} */ public function getParentFieldDescription($parentAssociationMapping, $class) { // Method is not used in Admin } } © Kirill chEbba Chebunin. Creara 2012
  • 30. Rich Model. Admin Interfaces. © Kirill chEbba Chebunin. Creara 2012
  • 31. Rich Model. Admin.Custom Model. interface Model { /** * Create mew object instance * * @return mixed */ public function createInstance(); /** * Save new object * * @param object $object * * @throws RuntimeException */ public function create($object); /** * Update existing object * * @param $object * @throws RuntimeException */ public function update($object); // Some other methods } © Kirill chEbba Chebunin. Creara 2012
  • 32. Rich Model. Admin.Custom Model. class UserModel implements Model { public function createInstance() { return new UserWrapper(); } public function create($wrapper) { $user = $this->userService->registerUser( $wrapper->getRegistrationData() ); $wrapper->setUser($user); } public function update($wrapper) { $user = $this->userService->updateUser( $wrapper->getUserData() ); $wrapper->setUser($user); } // Some other methods } © Kirill chEbba Chebunin. Creara 2012
  • 33. Rich Model. PROFIT! © Kirill chEbba Chebunin. Creara 2012
  • 34. Rich Model. Summary.  Object Logic in Object Class  Separate Domain Objects from View Object  Isolated Business Layer (Service Layer)  Delegation instead of Inheritance  Read 3rd Party Code © Kirill chEbba Chebunin. Creara 2012
  • 35. Rich Model. Pros & Cons.  OOPed (KISS, DRY, Patterns, blah, blah, blah)  Pros: – Less side effects – Less code duplication – Less chances to shoot your leg – Easy serialization – Easy API creation – Etc, etc, etc.  Cons: – More code – Codebase required – Hi shit sort out level © Kirill chEbba Chebunin. Creara 2012
  • 36. Rich Model. Questions? © Kirill chEbba Chebunin. Creara 2012