Best practice to access db from an Entity (first app tutorial)


#1

Hello,

I’m using Slim to write an API and I have followed this tutorial with TicketMapper and TicketEntity organisation :
https://www.slimframework.com/docs/tutorial/first-app.html

So, I would like to be able to access the database into a TicketEntity getter, by example :

class TicketEntity implements JsonSerializable
{ 

    ....

    public function getId() {
        // how to access $app->db here ? 
        return $this->id;
    }
}

I found a way by adding an db attribute on the TicketEntity class and pass $this->db from the TicketMapper like this :
new TicketEntity($params, $this->db)

… but it seems dirty because I need to perform it everytime TicketEntity is instantiated.

Is there a better way to access the database from an entity ?

Thanks !


#2

I haven’t spent much time following that tutorial, but it seems like you are asking about best practices around dependency injection. There is a good article about dependency injection with Slim, and some good conversation in the comments as well.


#3

Perhaps the TicketMapper is a more logical place for database calls? It already has access to the database through inheritance of Mapper. It will keep your entity agnostic of the database.


#4

Thanks all for your replies !