Method to Serialize Objects from appserver to web server without code duplication - php

I have a web-app-database 3 tier server setup. Web requests data from app, and app gets its data from the db then processes and returns it to web for display. Standard.
Currently all the data I serialize from app to web gets put into custom defined data structs that the web side then parses for display. In other words, say I have an order that I want to retrieve and send to web. I don't serialize the whole object, but rather build an array with the appropriate data elements while on the app server, then serialize that array over to the web servers.
Now, I am looking into serializing the entire order object over to the web server.
What is the best method you guys have found to serialize objects while maintaining separation of appserver and webserver code? I don't want my webservers having any code which accesses the DB, but I want them to reuse the classes that encapsulate my order and other data as much as possible.
To further refine my question (thanks to Glenn's response), I don't want my webservers to have any of the business logic around say the order class either, that only the appserver needs to know. The objects already use separate serialization to/from the database, and to/from the webservers.
Using the order example, on the appserver, an order should be able to cancel: ie
$order->cancel();
but on the webserver that method should not even be found. It shouldn't simply proxy back (directly) to the appserver order's cancel method, because user action requests should flow through the application's authorization and permissions checking layer.
So how do I get an order object on my webserver that has some (but not all) of the methods and properties of the object on my appserver, with little to no code duplication. One thing I've been thinking is to create a base class with a limited set of properties and methods. It would use an inner class to hold its properties, and I would require all data access to pass in and out of getters and setters. These would in turn call the getters and setters on the inner class.
The web and app servers could then independently extend the base class, and use a custom inner class to hold the properties. Then on the app side for instance, the inner class could be an ORM class extention that can persist data to the DB, and on the web side the inner class could be a simple properties holder class.
But the whole inner class thing seems a little clunky, so I'm still looking for better solutions.

Factor out format specific
serialization code into separate
classes using the Adapter
pattern. Your problem domain
classes become backing store
neutral.
Use relational database specific adapter classes on the app tier to serialize objects to and from the data tier.
Use HTML specific adapter classes on the web tier to serialize objects to and from the web browser.
Use XML (or whatever wire protocol friendly format you deem most appropriate) specific adapter classes on both the web and app tiers to serialize the objects between the web tier and the app tier.
You get extra points if you are clever enough to figure out how to make these adapter classes generic enough such that you don't need a different set of adapter classes per problem domain class.

If I understand your question correctly, you want to serialize the data of your objects, but when they are re-hydrated, they should be so into a different type of object (With limited and/or different functionality)?
You can do this in different ways, depending on what protocol you prefer. For example, you could use SOAP. You should then hydrate the objects into a different class on the client-side, than on the server-side. You could also use PHP's native serialization and either a) Have a different code base on the client (Could get confusing) or b) mock a bit around with the serialized string (Eg. replace the class-name). A crude example can be found in the comments for the PHP manual.

Related

Data passing between Controller and DAO within PHP MVC project

I'm working on a PHP MVC project, and the type of data interaction with the database is enough to facilitate the inclusion of a data access layer. The view will use Ajax to pass JSON objects to the controller for processing.
For the controller actions that require executing DAO functions, which is best:
Package incoming JSON into model objects and pass to DAO function
Pass incoming JSON data directly to DAO
Right now, I'm using option 1, since the views are being developed in parallel to the controller/DAO layers and packing the data within objects is easier for writing tests. When it comes to production, however, I am unsure if this is a good idea.
Using model objects to transfer data to DAO. The reasons I see are:
Better maintainability
Re-use models elsewhere and in many situations
Have Model specific methods in the model class and Data specific ones in the Data Access layer.
Sending back the model objects in JSON to the View all the time.
I think the option number 1 is the best one. Expecially if you are going to validate data server-side. You can have a controller action which validate and incapsulate data into models that will be used by DAO functions. This solution, also, will make your DAO method more re-usable in other parts of the application (example: every DAO-method will manipulate data models... like a standard behaviour)

MVC and the Repository Pattern: Roles of Controllers, Models, and Repositories?

So I've been studying the role of the repository pattern as a means of decoupling the persistence layer from my models in an MVC framework. Prior to this, I might have my UserModel calling active record methods directly in order to store/retrieve domain objects.
Here's a sketch of what I'm thinking in regards to the call stack in a request that should create a new User:
Here are my questions:
Is this a correct implementation of the repository pattern?
I understand that the controller should take the user's information from the request and pass it into the model. How does that usually happen? Should the controller create a User object and then pass that into the model? I sure as heck don't wanna just pass in an array of values into the model--nor do I want to pass in 15 arguments to the model method that creates a user.
In order for this pattern to really work, it looks like to me I would need to have a domain object that is just a simple data structure with no behavior and then if I'm using an ORM, I would have an ORM object which will describe how the object is persisted. Initially I resisted this because it feels like duplicate code, but if I'm really separating persistence from the business logic, this would be needed right? For example, what if I went with an in-memory store? I would no longer use the ORM object.
Am I thinking correctly here? Is this acceptable. Please help me connect the dots in my head.
1. Is this a correct implementation of the repository pattern?
I'm not sure where you been doing that research, but you have got it wrong.
Repositories as for separating the domain objects from data mappers.
There no such thing as "models". Model in MVC design pattern is one of the to main layers: presentation layer and model layer.
And the repository pattern is incompatible with active record (anti)pattern, which combines domain and storage logic in single instance, thus causing a major SRP violation.
To use a real world example for, when and how to use a repository here is an example:
You are creating some document management tool, where said documents can come from several sources (for example: local SQL database, SOAP service and cache). In this situation you create a repository, which deals with the "routing" of storage. It is the part of application, that decides which data mapper to use for storing/retrieving each document.
The goal of repository is to separate the domain logic from the interaction with storage. For the system, that was described above, a repository would also let add new data sources, without need to rewrite large amounts of code (if any). You could just add another type of mapper for the document.
2. Should the controller create a User object and then pass that into the model?
To begin with, controller itself should not create anything. Instead your controller should use a factory for acquiring instance of the object that you need. This factory can be provided to the controller through constructor or some other method. This is called: Dependency Injection (to learn more about it, watch this lecture).
Also, as noted above, model is a layer, not any specific class or object. The responsibility of controller is to alter the state of model layer (by passing data to it). You could interact with domain objects and mappers (or repositories) directly in the controller, but it would mean leaking some of the business logic in the controller. It is recommended to instead use services, which then manipulates said domain objects and storage related structures.
As for the issue with 10+ parameter, that you would require for creation of new user account, let's assume you have action with following footprint:
public function postUser( Request $request )
{
....
}
If the action gets called with specific Request instance, you have two options how to deal with large amount of parameters:
Wrap the instance in a decorator, which would let you call a single method for forming the data from request in a specific array. Then you pass this array to the service(s).
Form the array inside the controller's action and pass it, where th data is required.
The former solution is more suited for large scale applications, where such formation of data would be required repeatedly though-out the code. But in a small/medium projects the second option is the common-sense approach.
Thing is, the job of the controller is to take the user's input, and distribute it to the model layer and current view. And formation of such array fits right-in with this mandate.
3. (..) main object that is just a simple data structure with no behavior and then (..)
No. Domain object is not "simple data". It is where most of the domain business logic resides in the application.
And forget about magical ORMs. First step for implementing a repository is to separate the domain and storage logic. Domain object handles the validation and business rules, mapper deals with persistence and data integrity (small example here).
Another thing that you must realize is that repositories for web application do not really interact with in-memory persistence (apart from cache). Instead your repository would be juggling mappers for different data sources.
Should the controller create a User object and then pass that into the model?
I'm not sure what you mean by "pass that into the model" -- the User object is the model. "Controller" and "model" represent different layers in the design, they are not specific objects, and there shouldn't be a separate UserModel object as you mentioned.
The repository interface itself is generally considered part of the model, though the domain objects shouldn't be saving themselves -- this should be done in the controller.
Your controller's job would then be to interpret the request and create a User object, then use the repository to save the user:
$user = new User(...); // based on Request
$repository->save($user);
it looks like to me I would need to have a domain object that is just a simple data structure with no behavior
This is not true, you can and should encapsulate behaviour in your domain objects. As for how persistence is actually implemented, a good ORM should take care of most of the details and you shouldn't have to create additional classes by hand.

Use of models in FuelPHP?

I'm new to PHP frameworks and to start my venture I went to try FuelPHP. After a few days of testing around I understood how things work. Controllers control the actions, views control the $content and the template controls the layout. But what about models, What are they for?
Models are abstractions over data stored elsewhere, they encapsulate the data access through standard object creation, method calls, property access, etc. just like ordinary objects. The main idea here is that the controller (or whatever object that requires the data) doesn't need to know how to get the data or how it's stored. It could be stored in files, web (via webservice), database, whatever thing that could persist data. The data could be retrieved with webservice request, database query, file reading, etc.
For instance, "gimme student record with id 1" could be as simple as student := new student(1); and after that you have access to the student's name, address, etc. But how does the student retrieve its data? Where does it store the data? It's out of concern and could be tuned (or should be tunable) as needed.
models controle your data and have a direct contact with your db have a read here
You might have say
Contact With ID,Name,Detail and ContactType properties.
The idea is to keep it minimal it's basically something to cart around all the useful properties of an entity.
This is the current definition of MVC. Nothing about the backend in it. That would be some seperate library / dll that only knows about model, and how the underlying data is stored in the DB.

PHP OO - how to initialize your business objects?

By business model, or business objects, I mean plain old objects like a "User" with all their properties name, adress, ...; in addition to all the user properties let's say each user would have an "AppointmentBook" object, each book has a set of "TimeSlot" objects, etc.
The business model has objects with references between them, at least that's how I code a business model in Java.
Here comes the question:
To intialize my business objects, in Java, I would
fetch all of the data from DB only once during application
initialization,
map data from my DB to my business objects
store in memory (maps) and they would be shared across all the requests.
PHP's Share-Nothing-Architecture is confusing me for proper OO programming:
If I use the same logic, I would have to fetch all the objects from DB, for every request (I know I could still cache, but you don't cache all of your DB, it's not a question about caching but rather about the way of programming in PHP and its architecture).
So let's say that for one HTTP request, I just need the User properties and I don't need to access his appointment book. It would be a pitty to fetch all the data from the DB for all the objects the User makes reference to, as I just need his properties. This means that I will initialize PHP objects from my model with a lot of NULL values (NULL because of the objects contained in User that I won't load) which can later on lead to errors.
I was wondering how professional PHP developers usually use their business objects?
(I'm coming from Java)
UPDATE: It was kind of stupid to say that I would load the whole database into memory during application init in Java. What I rather meant is that, if I need to fetch a specific user, I could just load all of its data and that would be accessible through all the requests.
In PHP you do not keep all the data of your domain business model in the memory. Instead you only request from DB ( though cache, if needed ), the data you want.
Model layer in php should be built from multiple domain object and data mappers ( i assume, that part is not so different from Java ). If you need User details, then you fetch only that information from database/cache. You most likely will have a separate mapper just for dealing with user(s).
You display the information about that user, and forget about the query. Next request (when and if it comes) will require different information. Maybe you will want ContactList for that User ... then you really do not need user itself, only his user_id. Again, you let you mapper to fetch data into the domain object responsible for handling contact list, and if contact list contains User instances, then just create them, but leave in "unfetched" state (object knows only own user_id). Fetch them only if you really need to, and only the parts which you will use ins that "view".
P.S. you might have notices, I told that model later should be segmented, but quite often php developers just create single class of each DB table (which implements ActiveRecord) and call it "model". This is a result caused by Ruby on Rails influence on php framework developers, which, IMHO, is one of the worst things that has happened to PHP in past 5 years.
Your Java example implies your storing your entire databases content in memory. If your doing that, what's the point of the database? Why not just create all those object and memdump them for persistence.
If I use the same logic, I would have to fetch all the objects from DB, for every request
That's simply madness, you don't need to fetch anything, you create new instances when you need them and destroy them when you no longer need them.
So let's say that for one HTTP request, I just need the User properties and I don't need to access his appointment book.
That's easy, redesign your user. Your user needs it's properties and a property called appointmentBook which is simply an array of appointment book ids.
If you actually need those appointments you can fetch them from the database later.
This means that I will initialize PHP objects from my model with a lot of NULL values (NULL because of the objects contained in User that I won't load) which can later on lead to errors.
Not really, if this is the case your User object is too big. Make it smaller, you should load the entire user. Except of course the user has to be small enough for you to sensible load it.
If you don't want that then you can always create a UserProperties class and let every User have one. When you load the User you load the properties, but you also have an option to create the properties seperately.
Even in Java you would not load all data from the database into memory. You can however - as you write - often load more compared to short Transaction Scripts you normally have in PHP.
You models should be "clever" then to only load the data from the persistence storage that is needed to perform the requested action. This requires the object to be "clever" enough to lazy-load data probably.
This can be achieved with a Domain Model that knows enough about itself and a Data Mapper that knows enough about the storage for example.
There are other patterns as well which might suit your needs depending on the type of application, however a Domain Model together with Data Mapper is quite flexible.
An exemplary data mapper in the PHP world is Doctrine.

AJAX - PHP Communication patterns

I'm building a webapp in MySQL/PHP/Javascript.
In PHP, I've got all the classes from the domain od the problem which persist in the database.
In Javascript, there is a cache with objects from the last queries.
When an object in Javascript is updated by the user, it has to update itself in server-side. Which would be the best way to do this?
Should I create a class in PHP and Javascript for communication purposes? Should each object in Javascript send an AJAX query to a different php file depending on the class of the object it needs to update?
Are there any patterns to follow to solve this?
Creating a separate PHP file for each class would certainly be more maintainable if this is a project of any size at all. It would also allow you to do things like have different server-level authentication based on the classes.
On the JavaScript side, you definitely want some sort of AJAX library, whether you throw it together yourself (I did one once in about 50 lines of JavaScript) or use one of the ones out there. You may need a helper function or two that knows how to serialize the data (XML, JSON, delimited, whatever).
You can write object oriented code in JavaScript, and if you're doing that already, it makes sense to add a write() or updateServer() method to call the AJAX library with the right parameters for consistency. If you're not writing OO code, it still may make sense to have separate functions, but only if there's more than one place you need to persist these objects from.
Most AJAX frameworks (jQuery etc) will send an 'HTTP_X_REQUESTED_WITH' header set to 'xmlhttprequest'. I like to use this to decide which view to use.
This means the same url can be used to retrieve JSON, XML, or HTML snippet via JavaScript or to return a full document if a standard GET / POST request is made.
This means your app will simply revert to normal requests should the user have JS disabled.
I think you should have a look into the RESTful API with PHP and JavaScript. You address your domain model objects as unique resources (e.g. /application/books/1). If you only want to implement CRUD functionality a generic Controller that updates the corresponding domain model (e.g using an ORM tool like Doctrine) should be sufficient.
If you really want to have the same model on the client side in JavaScript depends on your Application. I like the idea of just managing a single JavaScript object on the client side which will be loaded via REST and then populated to HTML Forms and send back e.g. as JSON (or as a simple form submit) to the server. If the client side model idea appeals to you, I recommend to have a look at JavaScript MVC which has a quite interesting model implementation.

Categories