2

which one makes more sense?

This one is probably easier to use since you just can do $article->save();

 <?php

class Article
{
    private $author;

    public function __constructor(Author $author)
    {
        $this->author = $author;
    }

    public function save()
    {
        $database = ServiceLocator::getDatabase();
        //save article logic
    }
} 

Here you pass the object, resulting in having the control in you controller (or wherever you use it). Centralizing the control.

 <?php

class Article
{
    private $author;

    public function __constructor(Author $author)
    {
        $this->author = $author;
    }

    public function save(Database $database)
    {
        //Irgendwelche Logik um den Artikel zu speichern mittels $database
    }
} 

I'm prefering the last one, but I'm not entierly sure. Whats the state of art?

Thanks

xotix
  • 494
  • 1
  • 13
  • 41
  • 1
    I guess another way to think about it would be - which would be easier to unit test? edit: found this answer: http://stackoverflow.com/questions/1557781/whats-the-difference-between-the-dependency-injection-and-service-locator-patte – Cups Aug 27 '13 at 09:30
  • I don't understand both ways. Have you using the db object passed or statically called in each method needed a db in your classes, assuming you have Article, you have Author aswell. So in Author.save() for example do the same? – Royal Bg Aug 27 '13 at 09:30
  • RoyalBg yes. Cups thats also a godd argument. Anyway, the best practice is probably using e.g. doctrine. (data mapper) – xotix Aug 27 '13 at 12:54

1 Answers1

2

The article should not know how to save itself. The article now has too many responsibilities. Extract the logic that saves articles into a different class: a repository.

Steven
  • 166,672
  • 24
  • 332
  • 435
  • Of course, this is the best way, if you are using something like Doctrine which I actually going to do. There everything is nicely seperated. Very godo example of this can be found in the Symfony 2 Book – xotix Aug 27 '13 at 12:51