SlideShare a Scribd company logo
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

More Related Content

What's hot

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 framework
GOG.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 cliente
Leonardo 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 - 4Developers
Kacper 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 2
Kacper Gunia
 
Dependency Injection in PHP
Dependency Injection in PHPDependency Injection in PHP
Dependency Injection in PHP
Kacper 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 2015
Konstantin Kudryashov
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
Konstantin 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 Meetup
Kacper 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 mocking
Konstantin Kudryashov
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
Kris Wallsmith
 
Zero to SOLID
Zero to SOLIDZero to SOLID
Zero to SOLID
Vic Metcalfe
 
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 Pimple
Hugo 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 / XSolve
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)
Fabien Potencier
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
Jorn 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 DDD
Aleix 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
 

What's hot (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...
 

Viewers also liked

Application Layer in PHP
Application Layer in PHPApplication Layer in PHP
Application Layer in PHP
Per 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 Commons
Lars Jankowfsky
 
Introduction to architectural patterns
Introduction to architectural patternsIntroduction to architectural patterns
Introduction to architectural patterns
Georgy 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 Format
anishgoel
 
CQRS
CQRSCQRS
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
Ross Tuck
 
Soa Overview
Soa OverviewSoa Overview
Soa Overview
Terry Cho
 
Osi Model
Osi ModelOsi Model
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 matters
Lars Jankowfsky
 
N-Tier, Layered Design, SOA
N-Tier, Layered Design, SOAN-Tier, Layered Design, SOA
N-Tier, Layered Design, SOA
Sperasoft
 
Software engineering : Layered Architecture
Software engineering : Layered ArchitectureSoftware engineering : Layered Architecture
Software engineering : Layered Architecture
Muhammed Afsal Villan
 
Software Engineering - Ch11
Software Engineering - Ch11Software Engineering - Ch11
Software Engineering - Ch11
Siddharth Ayer
 
Software Architecture Patterns
Software Architecture PatternsSoftware Architecture Patterns
Software Architecture Patterns
Assaf Gannon
 
Layered architecture style
Layered architecture styleLayered architecture style
Layered architecture style
Begench Suhanov
 
Implementing DDD Concepts in PHP
Implementing DDD Concepts in PHPImplementing DDD Concepts in PHP
Implementing DDD Concepts in PHP
Steve Rhoades
 
Ch6 architectural design
Ch6 architectural designCh6 architectural design
Ch6 architectural design
software-engineering-book
 

Viewers also liked (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 to 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 Apps
Kris Wallsmith
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan 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 Applications
Sam Hennessy
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injection
Josh 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 scenarios
Divante
 
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
Rafael Dohms
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Rifat 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 Mapper
Jonathan Wage
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan 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. - PHPKonf
Rafael Dohms
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
Yevhen 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 PHP
mtoppa
 
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
Akihito Koriyama
 
SOLID PRINCIPLES
SOLID PRINCIPLESSOLID PRINCIPLES
SOLID PRINCIPLES
Luciano Queiroz
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
Kris 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 to 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)
 

Recently uploaded

Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
Aurora Consulting
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
rajancomputerfbd
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
RaminGhanbari2
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Erasmo Purificato
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
Stephanie Beckett
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
Matthew Sinclair
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
ishalveerrandhawa1
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
UiPathCommunity
 
Mitigating the Impact of State Management in Cloud Stream Processing Systems
Mitigating the Impact of State Management in Cloud Stream Processing SystemsMitigating the Impact of State Management in Cloud Stream Processing Systems
Mitigating the Impact of State Management in Cloud Stream Processing Systems
ScyllaDB
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
Mark Billinghurst
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
shanthidl1
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
Andrey Yasko
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
Tatiana Al-Chueyr
 
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024
Matthew Sinclair
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
Safe Software
 

Recently uploaded (20)

Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
 
Mitigating the Impact of State Management in Cloud Stream Processing Systems
Mitigating the Impact of State Management in Cloud Stream Processing SystemsMitigating the Impact of State Management in Cloud Stream Processing Systems
Mitigating the Impact of State Management in Cloud Stream Processing Systems
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
 
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
 

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