Z
Z
zvonok13372018-02-02 18:20:19
PHP
zvonok1337, 2018-02-02 18:20:19

How to stop creating class objects?

Hello, I decided to learn how to program at least a little in an adult way, and now .. I have a project in development, the following code is everywhere in the classes. I'm not comfortable that I have to create an object in __construct in order to use it in a class.

class TaskKey_Model
{
    private $database;
    private $user;
    private $task;

    public function __construct()
    {
        $this->database = new Database();
        $this->user = new User_Model();
        $this->task = new Task_Model();
        ..... и так далее
    }
}

Obviously, Database() can be taken out into a separate model, such as ActiveRecord, and simply inherited from it, but then what to do with User_Model and other things? How not to announce it all the time? (transfer everything to activerecord and call it statically, right?) and what other options are there

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor Vorotnev, 2018-02-02
@zvonok1337

Obviously, Database() can be moved to a separate model, such as ActiveRecord,

You already have it, in the Database class.
But this is not worth doing. From the word at all.
There is such a thing, Dependency Injection (DI). Read. Maybe don't smoke it right away. But it is necessary to understand and learn to work with it.
It should be like - you have a container that knows all your classes / services (they register in it or are pulled up using the Service Locator). It (the container) also holds instances of these classes - the first time the class is called, it is initialized 1 time and stored in the container. On subsequent calls, the container returns an already existing instance. You don't need to initialize services in constructors, it hard-wires your code and leads nowhere. Dependencies must be thrown through the constructor, parameters.

A
artem78, 2018-02-02
@artem78

You can use the Registry template.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question