xotix
xotix

Reputation: 530

Dependency injection vs. Service Locator to pass DB Object

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

Upvotes: 2

Views: 236

Answers (1)

Steven
Steven

Reputation: 172826

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.

Upvotes: 2

Related Questions