Let’s say I have a model that has ‘purchase’ method. The purchase method should take care of purchasing a product.
Signature of purchase
public function purchase($token, Model_Member $member, Model_Product $product, Model_Recipient $recipient);
To call this method, I need to make $member, $product, and $recipient in my controller. Is it considered a better approach to pass an array of values to the purchase so that purchase can make those required objects like below?
public function purchase($token, $member_id, $product_id, array $recipient);
in this case, purchase should pull up a member record from the database and make a model of it.
What’s the better approach?
1
Is it considered a better approach to pass an array of values to the
purchase so that purchase can make those required objects like below?
In general, I would say, no. But, like everything it depends.
If your domain doing the purchasing is significantly complex, IMHO, it is better to map all data into structures that the domain understands (so in your case, the entities) and then call purchase
.
This does a couple of beneficial things.
First, it means that the core business logic (purchasing) does not need the concern of how to hydrate data into objects. In other words, the domain entities do not need references to repositories.
Second, it means that you can map from many sources (database, web services, file systems) before calling the business domain. So, this sets up a nice separation of concerns around the core logic of your application.
For more on this. I recommend reading through the Onion Architecture series of blog posts.
Now, for the “It depends” part:
Every time that you add a logical layer to your application, you add complexity. In this case, you add the necessity to map into these domain objects before calling purchase
. So, if you are performing simple CRUD operations or forwarding on calls to some web service, then you probably don’t need to incur that cost.
0
Well the way I do it is like this:
The Controller:
- Should be responsible for interacting with the view and choosing the
appropriate Application service.
So read the input from the request object and create the appropriate
Application service.
The application service:
- Should be responsible for modeling your use case (i.e. your application logic), but holds no business logic. It orchestrates the application, but does no work itself.
The raw input passed from the controller is mapped to objects in this layer. Any domain service required is created in this layer and the appropriate method is invoked on this service.
The Domain Service, Entities and Value Objects:
- Should be responsible for modelling your domain logic and doing the actual work.
So in your case create the objects in the application service then pass them to the appropriate Domain service/entity/value object.