Eloquent workflow delivering data from database to client in a right way
PHP Frameworks History 1995 – 2004 •Dark Ages •No OOP •File per route •Superglobals •Mixed logic and templates •Manual file requires PHP 1.0 – 4.4
PHP Frameworks History 1995 – 2004 •Dark Ages •No OOP 2005 •CakePHP •Symfony 2006 •CodeIgniter •Zend Framework 2007 – 2008 •Kohana •Yii 2010 – 2011 •Symfony 2 •CI 2 •Laravel 2015 Yii2 (2014), Symfony 3.0, Zend Framework 3.0, Phalcon 2.0, Laravel 5.0 PHP 5.1 PHP 5.2 PHP 5.3 Composer (2012) PHP 5.6 (2014) PHP 7.0 PHP 1.0 – 4.4 Composer 1.0 (2016)
PHP Frameworks History • CakePHP • Symfony • CodeIgniter • Zend Framework • Kohana • Yii • Phalcon • Laravel MVC Frameworks • Simultaneous development • High cohesion • Low coupling • Ease of modification • Multiple views for a model
Model-View-Controller pattern •Data operations •App logic •Receives parameters from controller Model •Presentation •Output formatting •Receives data from model View •Input handling •Authorization •Validation Controller What is MVC?
What is Laravel? • Routing • Middleware • Controllers • Requests • Responses • Views • URL Generation • Session • Validation • Errors & Logging • Artisan Console • Broadcasting • Cache • Events • Database / ORM • File Storage • Mail • Notifications • Queues • Task Scheduling
Model-View-Controller pattern •Data operations •App logic •Receives parameters from controller Model •Presentation •Various output formatting •Receives data from model View •Input handling •Authorization •Validation Controller Laravel Framework •ORM Entity •Presenter Model (Eloquent) •Template engine •Partially interacts with model View •Handles input •Validation •Authorization •Data operations •App logic •and more… Controller ≠ ≠ ≠ Fat controller
Eloquent ORM • Relationships • Collections • Mutators • API Resources • Serialization
What does Eloquent Model do? • Interacts with data source via DBAL (Query builders) • Represents data Entity (ORM) • Provides presentation features • Pagination • Attribute mutations • JSON / Array serialization • Input modification • Attribute accessors • Possibly can contain any business logic
General issues of fat controllers using Eloquent Mixed input handling and app logic Unobvious logic Zero code reusability Strong dependency on template
Possible regressions N+1 Query Nullable values Exceptions Update/Insert Queries Passing Eloquent models to views might cause variety of regressions and errors, including: View Eloquent Model
More issues • Parts of business logic in one controller are often repeated in other controllers • Difficulty in centralizing data-related policies such as caching • An inability to easily test the business logic in isolation from external dependencies
How to deal with those issues? • Provide isolation between input handling, data operations and presentation. • Use dependency Injection to resolve required components. • Keep balance between reusability and complexity.
View Composers — V for MVC Pros: • Allow to implement View logic. • Can interact with data sources. • Allow dependency injections in constructor Cons: • Requires manual configuration • Composer classes are attached to template names
Repository Interface Repository pattern Data Source Repository Implementation Application Logic persist query Data Source Repository implementation Entity Data
Implementation of Data Layer with Repositories
Usage of Repositories Definition in Service Provider Usage via DI
Repository practices Bad • Returned instances are implementation of source-specific classes (e. g. Eloquent Models). • Interaction with application services. • Handling authorization and validation. Best • Return collections or single arrays or business entities related to repository. • Accept parameters as arguments or support criterias. • Isolate from app services, throw reasonable exceptions.
Testing Repository test Controller test Mock instances Run independent tests
What about presentation issues? • Unexpected behavior of magic getters. • Getters can execute queries • N+1 query issues. • Unloaded relations • Inconsistent data structure • Schema changes • Model class changes • Not flexible serialized output
Presenters and Transformers Presenter • Allows access to safe entity properties for presentation • Isolates entity from external access • Methods or getters usually return basic types • Constructed independently for each entity Transformer • Mostly used for API outputs. • Transforms entity into basic structure (e. g. array). • Usually single transformer instance is used to transform multiple entities.
Presenters and Transformers Presenter Wrapper Entity getter setter X Entity Transformer transformation basic structure Entity presentation View View Data Source Data Source
Implementation of Presentation Layer Presenters Transformers
Laravel 5.5 Resources • Native implementation of transformers. • Nested relationships • Conditional relationship attachment • Conditional parts • Response modifications
Presenters: • Laravel Auto Presenter • robclancy/presenter Transformers: • PHP League Fractal • Resources (Laravel 5.5)
Final look
Thank you! Viblo Deployment Day 26.11.2017 Roman Kinyakin

Eloquent workflow: delivering data from database to client in a right way

  • 1.
    Eloquent workflow delivering datafrom database to client in a right way
  • 2.
    PHP Frameworks History 1995– 2004 •Dark Ages •No OOP •File per route •Superglobals •Mixed logic and templates •Manual file requires PHP 1.0 – 4.4
  • 3.
    PHP Frameworks History 1995– 2004 •Dark Ages •No OOP 2005 •CakePHP •Symfony 2006 •CodeIgniter •Zend Framework 2007 – 2008 •Kohana •Yii 2010 – 2011 •Symfony 2 •CI 2 •Laravel 2015 Yii2 (2014), Symfony 3.0, Zend Framework 3.0, Phalcon 2.0, Laravel 5.0 PHP 5.1 PHP 5.2 PHP 5.3 Composer (2012) PHP 5.6 (2014) PHP 7.0 PHP 1.0 – 4.4 Composer 1.0 (2016)
  • 4.
    PHP Frameworks History •CakePHP • Symfony • CodeIgniter • Zend Framework • Kohana • Yii • Phalcon • Laravel MVC Frameworks • Simultaneous development • High cohesion • Low coupling • Ease of modification • Multiple views for a model
  • 5.
    Model-View-Controller pattern •Data operations •App logic •Receivesparameters from controller Model •Presentation •Output formatting •Receives data from model View •Input handling •Authorization •Validation Controller What is MVC?
  • 7.
    What is Laravel? •Routing • Middleware • Controllers • Requests • Responses • Views • URL Generation • Session • Validation • Errors & Logging • Artisan Console • Broadcasting • Cache • Events • Database / ORM • File Storage • Mail • Notifications • Queues • Task Scheduling
  • 8.
    Model-View-Controller pattern •Data operations •App logic •Receivesparameters from controller Model •Presentation •Various output formatting •Receives data from model View •Input handling •Authorization •Validation Controller Laravel Framework •ORM Entity •Presenter Model (Eloquent) •Template engine •Partially interacts with model View •Handles input •Validation •Authorization •Data operations •App logic •and more… Controller ≠ ≠ ≠ Fat controller
  • 9.
    Eloquent ORM • Relationships •Collections • Mutators • API Resources • Serialization
  • 10.
    What does EloquentModel do? • Interacts with data source via DBAL (Query builders) • Represents data Entity (ORM) • Provides presentation features • Pagination • Attribute mutations • JSON / Array serialization • Input modification • Attribute accessors • Possibly can contain any business logic
  • 11.
    General issues offat controllers using Eloquent Mixed input handling and app logic Unobvious logic Zero code reusability Strong dependency on template
  • 12.
    Possible regressions N+1 Query Nullablevalues Exceptions Update/Insert Queries Passing Eloquent models to views might cause variety of regressions and errors, including: View Eloquent Model
  • 13.
    More issues • Partsof business logic in one controller are often repeated in other controllers • Difficulty in centralizing data-related policies such as caching • An inability to easily test the business logic in isolation from external dependencies
  • 14.
    How to dealwith those issues? • Provide isolation between input handling, data operations and presentation. • Use dependency Injection to resolve required components. • Keep balance between reusability and complexity.
  • 15.
    View Composers —V for MVC Pros: • Allow to implement View logic. • Can interact with data sources. • Allow dependency injections in constructor Cons: • Requires manual configuration • Composer classes are attached to template names
  • 16.
  • 17.
    Implementation of DataLayer with Repositories
  • 18.
    Usage of Repositories Definitionin Service Provider Usage via DI
  • 19.
    Repository practices Bad • Returnedinstances are implementation of source-specific classes (e. g. Eloquent Models). • Interaction with application services. • Handling authorization and validation. Best • Return collections or single arrays or business entities related to repository. • Accept parameters as arguments or support criterias. • Isolate from app services, throw reasonable exceptions.
  • 20.
    Testing Repository test Controllertest Mock instances Run independent tests
  • 21.
    What about presentationissues? • Unexpected behavior of magic getters. • Getters can execute queries • N+1 query issues. • Unloaded relations • Inconsistent data structure • Schema changes • Model class changes • Not flexible serialized output
  • 22.
    Presenters and Transformers Presenter •Allows access to safe entity properties for presentation • Isolates entity from external access • Methods or getters usually return basic types • Constructed independently for each entity Transformer • Mostly used for API outputs. • Transforms entity into basic structure (e. g. array). • Usually single transformer instance is used to transform multiple entities.
  • 23.
  • 24.
    Implementation of PresentationLayer Presenters Transformers
  • 25.
    Laravel 5.5 Resources • Nativeimplementation of transformers. • Nested relationships • Conditional relationship attachment • Conditional parts • Response modifications
  • 26.
    Presenters: • Laravel AutoPresenter • robclancy/presenter Transformers: • PHP League Fractal • Resources (Laravel 5.5)
  • 27.
  • 28.
    Thank you! Viblo DeploymentDay 26.11.2017 Roman Kinyakin

Editor's Notes

  • #3 1. PHP in 1995. Quick to learn, created for web applications. 2. No OOP 3. Code mixed into templates. 4. Logic executed during rendering.
  • #4 Modern frameworks history began with PHP 5, which introduced OOP. Most of frameworks developed during 2005 — 2011 and created a basis for modern PHP approaches. 2015 was one of very important years. All current major versions of frameworks had been released that year. As well as php 7.0 and composer 1.0 in 2016. Laravel is a relatevely new framework and it’s first version was released in 2011 and was hardly used by anyone. It became really popular in 2013 and became one of the most widely used frameworks with release of Laravel 4.
  • #5 Why did I mention to all frameworks? They all are commonly named MVC frameworks because they mostly implement the pattern. You can see Model/View/Controller terms in each of them. Simultaneous development – Multiple developers can work simultaneously on the model, controller and views. High cohesion – MVC enables logical grouping of related actions on a controller together. The views for a specific model are also grouped together. Low coupling – The very nature of the MVC framework is such that there is low coupling among models, views or controllers Ease of modification – Because of the separation of responsibilities, future development or modification is easier Multiple views for a model – Models can have multiple views
  • #7 On this diagram we can see how Laravel’s popularity was rising over the years up until present days. Laravel got a significant boost and nowadays it is one of the easiest frameworks to begin with.
  • #22 1. Magic getters can access attributes, mutations, relations (both single and multiple) 2. Relations must be eager loaded and it happens in different parts of application 3. Any change to database schema or model configuration will cause possible failures of API clients or template errors 4. Only single toArray method available. Even with its modifications cannot provide enough flexibility for various outputs.
  • #23 1. Presenter wraps a model and provides
  • #27 Laravel Auto Presenter by Graham Campbell League Fractal – one of the most popular packages. Also used with Dingo API package