Services, Mappers,
Models: Enterprise
Thinking in PHP
Aaron Saray - MKEPUG
Why trust this guy?
              ● 21 years:
                programmer
              ● 12 years: internet
                programmer
              ● PHP Design
                Patterns - WROX
              ● Manager of Web
                Team @ LPi

              ● So handsome
Disclaimer!!
I don't have a BS CS. But that doesn't matter.
Best practices exist in programming.
Not everyone programs the same way.
There is more than one way to solve a problem.
Understand the core concepts, don't get hung
up on the minutiae.
For every solution I have, you can do it a
different way too. Yours may work too!
What are we talking
about today?
● Services, Mappers, Models
  ○ Go by a few different names
  ○ Mix and max

● Future proofing our solutions
  ○ separation of concerns
  ○ enterprise thinking

● Making life easier by investments up front
What are Models?
● Represent a true entity in your business
   ○ user, visitor
   ○ box, ps3, blu-ray movie

● They know about themselves in their current state
   ○ they don't know if they're incomplete
   ○ they don't know how they're populated


● Do logic from the business
   ○ logical transformation that makes sense in your
     realm
What are Models? (cont)
Examples:

● User:
  ○ first name, last name, age
     ■ calculates fullname
     ■ calculates user requires adult consent

● PS3
  ○ serial number, model number
    ■ calculates date manufactured from serial #
What are Models? (cont 2)
Out of the realm of model:

● Have I been saved to the database?

● Have I been created from a form input or a
  MySQL result set?

● How can I get more information about
  myself?
What are Mappers?
● Mappers map data to a model

● Mappers know about models. Models do not
  know about mappers.

● Mappers are dependent on the data source
  ○ Swap data sources? Introduce a new mapper!
What are Mappers? (cont)
● Mapper interprets a request and creates a
  corresponding call to MySQL
  ○ request for a package with ID #7, create MySQL call
    for that, get results, apply to the model I received.

● Mapper applies data results to a model in
  the proper way

● Mappers are very foreign to most
  ○ Most Frameworks provide generic ones with "magic"
  ○ Most custom code lacks mappers
What are Services?
● Services are the way that the rest of the
  code requests objects

● Services know about a Model, and it's
  corresponding Mapper. Models and
  Mappers don't know about services.

● Services interpret requests, create new
  models, and invoke mappers to populate
  models.
What are Services? (cont)
● Services understand logical identifiers of
  models
   ○ fetchById()

● Services can create containers or single
  result sets
   ○ fetchPaginator(), fetchByEmail()

● Services retrieve and persist data
   ○ fetching / saving / updating
What are Services? (cont2)
● Services rarely change once created
  ○   Mappers change with new data sets
  ○   Models change with new logic
  ○   Retrieval methods are relatively stoic
  ○   Persistence methods CAN change more often
Show me an example!
 Show User
 Details for
  User # 5

  UserService::fetchById(5)          new User();

                              UserMapper MySQL query
                                      ID = 5
Yay!


                              Apply fetchAssoc to model
Example Code:
● It's easy for me to show you a perfect
  situation
  ○ But unless you're making something brand new, it's
    not really feasible

● Let's look at some novice PHP code
  ○ and refactor to Enterprise Thinking code!
What we're accomplishing?
● Will use MySQL to retrieve user information

● Want to show the full name, email address,
  of user 5 on the screen

●   Don't do this!
Controller Code
Class Code - Part 1
Class Code - Part 2
So What's Wrong
With This?
● From my introduction, you can spot some
  things

● What are they?
Bad Things:




         Seems like the User model is in charge of retrieving
         data based off the ID
More Bad Things
                  I'm not sure if this data is
                  coming from the database -
                  where the rest is. It's a one-off




                           Yup, the user has to
                           populate itself, plus it
                           has to understand that
                           this is a key.
More Bad Things:

                                                        The model is now forever
                                                        tied to the data source,
                                                        and must be modified if it
                                                        changes.




                                                               Here logic is being done
 The model is mapping itself to the data set results.          in the model. That's fine.
 If a data source is changed, even the creation of             However, it's using map-
 "full name" is lost.                                          able data. :(
Save me!
● Model should be only concerned with itself
   ○ full name is logic

● Mapper should connect and retrieve MySQL
  data and apply it to the model

● Service should be initialized in the controller
  and retrieve the proper user of ID 5
A Simpler User Model
                                                 No population. Only stores data,
                                                 and calculations (see below).




   Creating a full name is actually a logical calculation. For example,
   American name, this is correct.
   Latino heritage full name may contain multiple last names.
Mapper for MySQL
            Only for MySQL - this is important!!



                   Mapper creates connection.




                                Mapper understands ID,
                                but has to receive a new
                                user instance. Can't
                                create one itself.



                                  Retrieve data, and
                                  apply it to the object.
User Service


                           Initialize a User
                           for the mapper.

                                               Get new
                                               mapper.
                                               Send to
                                               mapper the
                                               user and the
                                               data access
                                               pointer
                                               (user id).
               Return the properly
               populated model to
               the requestor.
Updated Controller Code
                     Instead of creating a new
                     User object, create a
                     new service object.
                     Then, ask the service for
                     the user of ID #5.




                  Don't forget! The full
                  name is not really a
                  property - so now it's a
                  method call in our code.
What was gained?
● Model now only deals with business
  information

● Service can easily ask for and interpret
  requests for particular models

● Bound our mapper to MySQL
   ○ made it easier to swap out data sources
Ruh Roh!
● Requirements change!

● Choose your poison:
  ○ your boss said to new partner "it won't be a big deal,
    of COURSE we can use your feed instead of our
    database"

  ○ your client says "omg omg omg we now need to use
    this feed because it's the newest thing do it now!"
Requirement Change:
Instead of using MySQL, now all user data
must be retrieved from a XML feed request.

Using a GET request, call the feed URL with a
parameter of the user ID.

You can expect an XML document with one
node with the attribute as the ID, and nodes for
the user information.
What We Used to
Have to Do
● Back in the day
  ○   Open up the User class and modify code
  ○   Possibly delete old code and lose it
  ○   Modify the model even though nothing has changed
  ○   Cry
What we will do now
● Create a new mapper class named after the
  Remote XML feed
  ○ note: we don't have to get rid of any old code
    ■ what if boss changes his mind back?

● Change one line in Service class

● To summarize:
  ○ One line change of existing code
  ○ Rest is brand new code
    ■ SUCH A SMALL IMPACT
Fine: I did change the
controller




           The only change is including the new file instead. A good
           autoloader would have made this a non-issue. But, I had
           to show you this. Ignore it as a required 'change'
One line change in Service


                     See? Simple
                     little change. If I
                     want to go back
                     to the old code, I
                     can change this
                     mapper back.
New Mapper Class

                   Same method
                   call, just
                   different data
                   retrieval and
                   preparation.
Final Thoughts
● Probably should create a mapper interface -
  so that all mappers now have a mapFromId()
  method

● It is easy to swap back and forth with
  different data sources

● Business req changes are now easier
   ○ least impact on each individual part
The End

                       Aaron Saray
             Milwaukee PHP Web Developer


Questions?       http://aaronsaray.com

                         @aaronsaray

Enterprise PHP: mappers, models and services

  • 1.
  • 2.
    Why trust thisguy? ● 21 years: programmer ● 12 years: internet programmer ● PHP Design Patterns - WROX ● Manager of Web Team @ LPi ● So handsome
  • 3.
    Disclaimer!! I don't havea BS CS. But that doesn't matter. Best practices exist in programming. Not everyone programs the same way. There is more than one way to solve a problem. Understand the core concepts, don't get hung up on the minutiae. For every solution I have, you can do it a different way too. Yours may work too!
  • 4.
    What are wetalking about today? ● Services, Mappers, Models ○ Go by a few different names ○ Mix and max ● Future proofing our solutions ○ separation of concerns ○ enterprise thinking ● Making life easier by investments up front
  • 5.
    What are Models? ●Represent a true entity in your business ○ user, visitor ○ box, ps3, blu-ray movie ● They know about themselves in their current state ○ they don't know if they're incomplete ○ they don't know how they're populated ● Do logic from the business ○ logical transformation that makes sense in your realm
  • 6.
    What are Models?(cont) Examples: ● User: ○ first name, last name, age ■ calculates fullname ■ calculates user requires adult consent ● PS3 ○ serial number, model number ■ calculates date manufactured from serial #
  • 7.
    What are Models?(cont 2) Out of the realm of model: ● Have I been saved to the database? ● Have I been created from a form input or a MySQL result set? ● How can I get more information about myself?
  • 8.
    What are Mappers? ●Mappers map data to a model ● Mappers know about models. Models do not know about mappers. ● Mappers are dependent on the data source ○ Swap data sources? Introduce a new mapper!
  • 9.
    What are Mappers?(cont) ● Mapper interprets a request and creates a corresponding call to MySQL ○ request for a package with ID #7, create MySQL call for that, get results, apply to the model I received. ● Mapper applies data results to a model in the proper way ● Mappers are very foreign to most ○ Most Frameworks provide generic ones with "magic" ○ Most custom code lacks mappers
  • 10.
    What are Services? ●Services are the way that the rest of the code requests objects ● Services know about a Model, and it's corresponding Mapper. Models and Mappers don't know about services. ● Services interpret requests, create new models, and invoke mappers to populate models.
  • 11.
    What are Services?(cont) ● Services understand logical identifiers of models ○ fetchById() ● Services can create containers or single result sets ○ fetchPaginator(), fetchByEmail() ● Services retrieve and persist data ○ fetching / saving / updating
  • 12.
    What are Services?(cont2) ● Services rarely change once created ○ Mappers change with new data sets ○ Models change with new logic ○ Retrieval methods are relatively stoic ○ Persistence methods CAN change more often
  • 13.
    Show me anexample! Show User Details for User # 5 UserService::fetchById(5) new User(); UserMapper MySQL query ID = 5 Yay! Apply fetchAssoc to model
  • 14.
    Example Code: ● It'seasy for me to show you a perfect situation ○ But unless you're making something brand new, it's not really feasible ● Let's look at some novice PHP code ○ and refactor to Enterprise Thinking code!
  • 15.
    What we're accomplishing? ●Will use MySQL to retrieve user information ● Want to show the full name, email address, of user 5 on the screen ● Don't do this!
  • 16.
  • 17.
  • 18.
  • 19.
    So What's Wrong WithThis? ● From my introduction, you can spot some things ● What are they?
  • 20.
    Bad Things: Seems like the User model is in charge of retrieving data based off the ID
  • 21.
    More Bad Things I'm not sure if this data is coming from the database - where the rest is. It's a one-off Yup, the user has to populate itself, plus it has to understand that this is a key.
  • 22.
    More Bad Things: The model is now forever tied to the data source, and must be modified if it changes. Here logic is being done The model is mapping itself to the data set results. in the model. That's fine. If a data source is changed, even the creation of However, it's using map- "full name" is lost. able data. :(
  • 23.
    Save me! ● Modelshould be only concerned with itself ○ full name is logic ● Mapper should connect and retrieve MySQL data and apply it to the model ● Service should be initialized in the controller and retrieve the proper user of ID 5
  • 24.
    A Simpler UserModel No population. Only stores data, and calculations (see below). Creating a full name is actually a logical calculation. For example, American name, this is correct. Latino heritage full name may contain multiple last names.
  • 25.
    Mapper for MySQL Only for MySQL - this is important!! Mapper creates connection. Mapper understands ID, but has to receive a new user instance. Can't create one itself. Retrieve data, and apply it to the object.
  • 26.
    User Service Initialize a User for the mapper. Get new mapper. Send to mapper the user and the data access pointer (user id). Return the properly populated model to the requestor.
  • 27.
    Updated Controller Code Instead of creating a new User object, create a new service object. Then, ask the service for the user of ID #5. Don't forget! The full name is not really a property - so now it's a method call in our code.
  • 28.
    What was gained? ●Model now only deals with business information ● Service can easily ask for and interpret requests for particular models ● Bound our mapper to MySQL ○ made it easier to swap out data sources
  • 29.
    Ruh Roh! ● Requirementschange! ● Choose your poison: ○ your boss said to new partner "it won't be a big deal, of COURSE we can use your feed instead of our database" ○ your client says "omg omg omg we now need to use this feed because it's the newest thing do it now!"
  • 30.
    Requirement Change: Instead ofusing MySQL, now all user data must be retrieved from a XML feed request. Using a GET request, call the feed URL with a parameter of the user ID. You can expect an XML document with one node with the attribute as the ID, and nodes for the user information.
  • 31.
    What We Usedto Have to Do ● Back in the day ○ Open up the User class and modify code ○ Possibly delete old code and lose it ○ Modify the model even though nothing has changed ○ Cry
  • 32.
    What we willdo now ● Create a new mapper class named after the Remote XML feed ○ note: we don't have to get rid of any old code ■ what if boss changes his mind back? ● Change one line in Service class ● To summarize: ○ One line change of existing code ○ Rest is brand new code ■ SUCH A SMALL IMPACT
  • 33.
    Fine: I didchange the controller The only change is including the new file instead. A good autoloader would have made this a non-issue. But, I had to show you this. Ignore it as a required 'change'
  • 34.
    One line changein Service See? Simple little change. If I want to go back to the old code, I can change this mapper back.
  • 35.
    New Mapper Class Same method call, just different data retrieval and preparation.
  • 36.
    Final Thoughts ● Probablyshould create a mapper interface - so that all mappers now have a mapFromId() method ● It is easy to swap back and forth with different data sources ● Business req changes are now easier ○ least impact on each individual part
  • 37.
    The End Aaron Saray Milwaukee PHP Web Developer Questions? http://aaronsaray.com @aaronsaray