1

I'm just beginning to experiment with the Slim framework and RedBean ORM in PHP.

Let's say I have a CommentService registered with Slim's Dependency Injection Container. Also, I have a data model named Comment_Model which is used by RedBean to represent comments stored in a database.

Now, from my route/controller, I want to add a new comment to the database. This is where I'm a bit confused - what would be the "best practice" way of passing information from the route/controller to the service method?

I can think of at least three different ways to do this;

1 - Use an instance of Comment_Model to supply the data:

class CommentService {

    public function add(\App\Data\Model\Model_Comment $comment){
        // Let the ORM persist the data        
    }

}

This feels a bit like abusing the data model entity class though - isn't it meant to be instantiated by the ORM, not as a convenience feature to pass around new, unpersisted data?

2 - Separate parameters

class CommentService {

    public function add($userId, $message, $replyToId){
        // Let the ORM create a proper data model and persist the data 
    }

}

It works when there are only three parameters, but for something more complex than a comment it could easily get out of hand...

3 - Create a Data Transfer Object

class CommentDTO{
    public $userId;
    public $message;
    public $replyToId;
}


class CommentService {

    public function add(\App\Data\DTO\CommentDTO $comment){
        // Let the ORM create a proper data model and persist the data
    }

}

Isn't it a bit overkill to create a DTO for local use?

Are there any hard rights and wrongs here? What is the "normal" way to do things like this?

Magnus
  • 17,157
  • 19
  • 104
  • 189
  • 1
    I think your first option is ideal. I pretty much use the same model of Request/Service/Model and so far so good, although I'm using the Eloquent db model rather than RedBean. I like keeping the service methods as simple as possible and allow the controllers to only handle calls to the service based on the request. – Rob Jan 24 '17 at 15:49
  • @Rob Thanks, I ended up going with the models in the end. At first I started out using DTO's but it turned out to add unnecessary complexity for something that is much more elegantly done using models. – Magnus Feb 04 '17 at 09:12

0 Answers0