ZF models correct use - zend-framework

I am struggling with how to understand the correct usage of models. Currently i use the inheritance of Db_Table directly and declare all the business logic there. I know it's not correct way to do this.
One solution would be to use Doctrine ORM, but this requires learning curve and all the current components what i use needs to be rewritten paginator and auth. Also Doctrine1 adds a another dozen classes which need to be loaded.
So the current cleanest implementation what i have seen is to use the Data Mapper classes between the so called model and DbTabel. I haven't yet implemented this as it seems to head writing another ORM. But example could be something this: SQL table User
create class with setters, getters, business logic here /model/User.php
data mapper /model/mapper/UserMapper.php, the funcionality is basically writing all the update, save actions in here.
the data source /model/DbTable/User.php extends the Db_Table_Abstract
Problems are with relationships between other models.

I have found it beneficial to not have my models extend Db_Table, but to use composition instead. That means my model 'has a' Db_Table rather than 'is a' Db_Table.
That way I find it much easier to reference multiple tables in the same model, which is a common requirement. This is enough for a simple project. I am currently developing a more complex application and have used the Data Mapper pattern and have found that it has simplified my code more than I would have believed.
Specifically, I have created a class which provides all access to the database and exposes methods such as getUser() etc.. That way, if the DB changes, or my client wants something daft like storing records in XML or we split the servers or something I only have to rewrite one class.
Again, my models do not extend this class, but have an instance of it assigned as a property during construction.

I would say the 'correct' way depends on the situation. Following the YAGNI and KISS principles, it is not good to over-complicate your model setup unless you really believe that it will benefit you in the long run.
What is the application you are developing? How is your current setup of extending Db_Table holding you back?

Related

Replacements to hand-rolled ADO.NET POCO mapping?

I have written a wrapper around ADO.NET's DbProviderFactory that I use extensively throughout my applications. I also have written a lot of code that maps IDataReader rows to POCOs. However, as I have tons of classes the whole thing is getting to be a pain in the ass to maintain.
I have been looking at replacing the whole she-bang with a micro-orm like Petapoco. I have a few queries though:
I have lots of POCOs that contain other POCOs in them as properties. How well does the Petapoco support this?
Should I use a ORM like Massive or Simple.Data that returns a dynamic object and map that to a POCO?
Are there any approaches I can take to the whole mapping of rows to POCOs? I can't really use convention-based tools as my database isn't particularly consistent in how it is designed.
How about using a text templating/code generator to build out a lightweight persistence layer? I have a battle-hardened open source project called TextMetal to generate the necessary persistence layer based on tried and true architectural decisions. The only lacking thing is object to object relations but it does support query expressions and works well with poorly designed data schemas.
You can see a real world project that uses the above tool call Can Do It For.
Feel free to ask me about any design decisions once you take a look-sse.
Simple.Data automagically casts its dynamic type to static types. It will map nested properties as long as they have been eager-loaded using the .With method. So for example
Customer customer = db.Customer.WithOrders().Get(42);
would populate the Orders property of the customer object.
Could you use QueryFirst, or modify it? It takes your sql and wraps it in vanilla ADO code, generated at design time. You get fresh POCOs from your result schema every time you save your file. Additionally, you can choose to test all queries and regenerate all wrappers via the option in the tools menu. It's dependent on Sql Server and SqlClient, so unless you do some modification, you'll lose DbProviderFactory.

How to do filtering for many entities of many DataServices in one common class?

Tier database and every single table has a DataSetId and I absolutely want to be sure that the data is always partitioned correctly.
Currently I'm using the QueryInterceptor attribute but it's messy and overly repetitive and prone to errors. Some new Dev could add a new table and forget to filter by DataSetId, or just rename a table. So I've put this in a base class but the IQuerable properties of my repository are never called.
I have a "CoreRepository" class that inherits from ObjectContext, and each of my IQueryable collections uses "CoreObjectSet". CoreObjectSet extends ObjectSet by always adding an expression to filter by DataSetId. When used directly this works fine. But when used for a DataService the Get accessor for the collections on the Repository are never called by the DataService. It appears to be cheating and not using them at all and accessing the data directly.
Is there a way to get the DataService to access through the repository class correctly (And still get the efficiency of passing through the query as SQL)?
If this is the behaviour why even make DataService of T anyway if it's not even going to use the class? For the ADO team to just ignore it and use the edmx directly seems like a hack.
Thanks
Aaron
Looks like the only way around it is to use a T4 template to generate the DataService. I much prefer a base class or some kind of reusable handler but ADO has given me no choice here.

Business logic in Entity Framework POCOs using partial classes?

I have business logic that could either sit in a business logic/service layer or be added to new members of an extended domain class (EF T4 generated POCO) that exploits the partial class feature.
So I could have:
a) bool OrderBusiness.OrderCanBeCancelledOnline(Order order) .. or (IOrder order)
or
b) bool order.CanBeCancelledOnline() .. i.e. it is the order itself knows whether or not it can be cancelled.
For me option b) is more OO. However option a) allows more complex logic to be applied e.g. using other domain objects or services.
At the moment I have a mix of both and this doesn't seem elegant.
Any guidance on this would be much appreciated!
The key thing about OO for me is that you tell objects to do things for you. You don't pull attributes out and make the decisions yourself (in a helper class or other).
So I agree with your assertion about option b). Since you require additional logic, there's no harm in performing an operation on the object whilst passing references to additional helper objects such that they collaborate. Whether you do this at the time of the operation itself, or pre-populate your order object with those collaborating entities is very much dependent upon your current situation.
You can also use extension methods to the POCO's to wrap your bll methods.
So you can keep using your current bll's.
in c# something like:
public static class OrderBusiness <- everything must be static, class and method
{
public static bool CanBeCancelledOnline(this Order order) <- notice the 'this'
{
logic ...
And now you can do order.CanBeCancelledOnline()
This is likely to depend on the complexity of your application and does require some judgement that comes with experience. The short answer is that if your project is anything more than a pretty simple one then you are best off putting your logic in the domain classes.
The longer answer:
If you place your logic within a service layer you are affectively following the transaction script pattern, and ending up with an anaemic domain model. This can be a valid route, but it generally works best with simple and small projects. The problem is that the transaction script layer (your service layer) becomes more complicated to maintain as it grows.
So the alternative is to create a rich domain model that contains the logic within it. Keeping logic together with the class it applies to is a key part of good OO design, and in a complex project pretty essential. It usually requires a bit more thought and effort initially, which is why for very simple projects people sometimes use the transaction script pattern.
If you are unsure about which to go with it is not normally a too difficult job to refactor your logic to move it from your service layer to the domain, but you need to make the call early enough that the job is not too large.
Contrary to one of the answers, using POCO classes does not mean you can't have business logic in your domain classes. POCO is about not applying framework specific structures to your domain classes, such as methods and interfaces specific to a particular ORM. A class with some functions to apply business logic is clearly still a Plain-Old-CLR-Object.
A common question, and one that is partially subjective.
IMO, you should go with Option A.
POCO's should be exactly that, "plain-old-CLR" objects. If you start applying business logic to them, they cease to be POCO's. :)
You can certainly put your business logic in the same assembly as your POCO's, just don't add methods directly to them, create helper classes to facilitate business rules. The only thing your POCO's should have is properties mapping to your domain model.
Really depends on how complex your business rules are. In our application, the busines rules are very straightforward, so we use Option A.
But if your business rules start to get messy, consider using the Specification Pattern.

zend models architecture

Let's say I have two tables in a database: projects and users. I create two models, that extend Zend_Db_Table_Abstract: Model_DbTable_Users and Model_DbTable_Projects.
Now, is it a good pattern to create an instance of Model_DbTable_Projects inside the Model_DbTable_Users class ? In other words: is it OK to put any logic in this model, or should I create another class, that uses Model_DbTable_Users and Model_DbTable_Projects?
I use to put all the logic in models, that extend Zend_Db_Table_Abstract, but in large projects it can make code very unclean. So, can you give me any advice on models architecture(links on articles would be great!).
I was the project lead for the Zend Framework project through version 1.0. My contributions were mainly in the Zend_Db component.
I frequently advise that people should use the Domain Model pattern and avoid the Anemic Domain Model antipattern. Remember that a Table is not a Model.
Your Model is a class (extending no base class) for code that encapsulates your business logic. The relationship between a Model and a Table isn't IS-A, it's HAS-A (or HAS-MANY). The Model treats database persistence as an implementation detail. The consumer of a Model should have no clue about your database structure (this allows you to change database structure without changing the Model's interface).
I'm basically repeating the answer I gave to Models in the Zend Framework.
Here is some more reading:
http://weierophinney.net/matthew/archives/202-Model-Infrastructure.html
http://blog.astrumfutura.com/archives/373-The-M-in-MVC-Why-Models-are-Misunderstood-and-Unappreciated.html
http://n4.nabble.com/Another-Model-Design-Thread-td670076.html

Does the DataMapper pattern break MVC?

I have been reading up on multiple PHP frameworks, especially the Zend Framework but I am getting confused about the proper way to go forward.
Zend Framework does not use ActiveRecords but instead uses the Table Data Gateway and Row Data Gateway pattern, and uses a DataMapper to map the contents of the Row Data Gateway to the model, because ActiveRecord breaks down when your models don't have a 1:1 mapping to your database tables. There is an example of this in the Zend Quickstart guide.
To me, their example looks very bloated with a ton of getters and setters all over the place. I came across various blog posts about Domain Driven Design arguing that using so many getters and setters is bad practice because it exposes all the inner model data to the outside, so it has no advantage over public attributes. Here is one example.
My question: If you remove those getters and setters, how will you render your views? At some point the data has to hit the view so you can actually show something to the user. Following the DDD advice seems to break the separation between M and V in MVC. Following the MVC and Zend example seems to break DDD and leaves me typing up a whole lot of getters, setters and DataMappers for all my models. Aside from being a lot of work it also seems to violate DRY.
I would really appreciate some (links to) good examples or more information about how it all fits together. I'm trying to improve my achitecture and design skills here.
Using Value Objects, you can eliminate some of those public setter methods. Here's a description of the difference between Entity and Value Objects. Value Objects are immutable and often tied to an Entity. If you pass all values in with the constructor, you don't need to set these properties from external code.
Something extra, not directly related to an answer, but more focused on DDD:
(Disclaimer: The only thing I know about the Zend Framework is what I read in the linked article.) The Zend Framework is using DataMappers instead of Repositories. Is this really DDD-ish? Well, Fowler's interpretation of a Repository might say no. However, Eric Evans states that a DDD Repository can be very simple. At its simplest, a Repository is a DataMapper (See DDD book). For something more complex and still DDD, see the Fowler article. DDD has a conceptual Repository that may differ from the pattern definition.
I urge you to continue reading about Domain-Driven Design. I think there's a flaw in the assumption that getters and setters violate DDD. DDD is about focusing on the domain model and best practices to accomplish that. Accessors are just a minor detail.
You don't need to implement all the getters/setters, you can use__get() and __set(). What's the problem then?
From my reading of the post, the question is more philosophical rather than practical.
I don't have the time to write in depth, but here is my two cents. While I agree that you want to limit the number of get and set requests because a class should hide its internals, you also need to take into account the Java and PHP are different tools and have different purposes. In the web environment your classes are being built and taken down with each request and therefore the code you write should not depend on huge classes. In the article you pointed out the author suggests placing the view logic in the class. This probably does not makes sense on the web since I will likely want to present the view in multiple formats (rss, html, etc...). Using accessor methods (get & set) therefore is a necessary evil. You still want to use them thoughtfully so that you don't shoot yourself in the foot. The key is to try to have your classes do the work for you instead of trying to force them to do work externally. By accessing your properties with a method instead of directly you hide the internals which is what you want.
Again, this post could use some examples, but I don't have the time right now.
Can someone else provide a few examples of why accessor methods aren't evil?
There are two approaches here: What I call the "tell don't ask approach", and the other is the ViewModel/DTO approach.
Essentially the questions revolves around what is the "model" in your view.
Tell don't ask requires that the only way an object can be externalized, is from the the object itself. In other words, to render an object, you would have a render method, but that render method would need to talk to an interface.
Something like this:
class DomainObject {
....
public function render(DomainObjectRenderer $renderer) {
return $renderer->renderDomainObject(array $thegorydetails);
}
}
In the context of Zend Framework, you can subclass Zend_View and have your subclass implement this interface.
I've done this before, but its a bit unwieldy.
The second option is convert your domain model in to a ViewModel object, which is like a simplified, flattened out, "stringed out" view of your data, customized for each specific view (with one ViewModel per view), and on the way back, convert the POST data to an EditModel.
This is a very popular pattern in the ASP.NET MVC world, but its also similar to the class "DTO" pattern used to transfer data between "layers" in an application. You would need to create mappers to do the dirty work for you (not unlike a DataMapper, actually). In PHP 5.3, you can use reflection to change private properties, so your DomainObject doesn't even need to expose itself either!
Implementing getters and setters has two advantages, in my eyes:
You can choose which properties to make public, so you don't necessarily have to expose all of the model's internals
If you use an IDE with autocomplete, all the available properties will be a TAB away when you start typing "get" or "set"—this alone is reason enough for me.