samedi 15 août 2015

How to identify entities in model, with data received from User (View)

I'm writing an application using an MVC (or rather MVP) framework (Symfony2) and an ORM (Doctrine2), and trying keep the design of the application as decoupled as possible, I especially want to keep the knowledge of the "Controller" from the "Model" as little as possible.Now Here is the Question:
Let's say I have a Product Entity that has two Unique fields: id and code.The Identifier of the Product Entity is id, but users know Products by their code. So if I have a form with two fields: "name" and "code", which will ultimately cause a name change to a Product with the given code, how should I get this info my model layer? The solutions I have in mind will involve three (or two) classes. 1. The Controller 2. The ProductUpdater 3. The ProductFinder. Now here are the different approaches I have in mind:

  1. The Controller knows that the received data is for a Product with the received code, so it will first find that Product or it's id using the ProductFinder and then pass it to the ProductUpdater along with the "name".e.g:

    // the controller
    // we already have $name and $code from the request
    // the controller knows that the received data references the product by it's code
    // so it calls findByCode on the product finder
    $product = $this->productFinder->findByCode($code);
    $this->productUpdater->update($product, $name);
    
    

  1. We inject a custom ProductFinder into the Controller that knows it should find products by their code.

    // this product finder is injected into the controller
    // it is actually a decorator for another product finder
    // that finds products by their attributes
    public function find($id){
      return $this->decoratedProductFinder->findByCode($id);
    }
    
    //in the controller
    // $id and $name are generated from the request data
    // the controller doesn't know the received data is for the code of a product so we have the variable $id
    $product = $this->productFinder->find($id);
    $this->productUpdater->update($product, $name);
    
    

This approach to me seems the worst of all, since it's really obfuscating and depends a lot on the Dependency Injection being Done.


  1. The ProductUpdater and the Controller both know that the received data is for Product's code so it will be something like this:

    // in the controller
    // we pass the data directly to the productUpdater
    $this->productUpdater->updateByCode($code, $name);
    
    

  1. only the ProductUpdater knows about the data, it is like approach number 2.

    // in the controller
    $this->productUpdater->update($id, $name);  
    
    

Currently I'm mostly using approach no.3. What is the best approach among the given choices and what other alternatives are there?

Aucun commentaire:

Enregistrer un commentaire