When moving a formal procedure to object-oriented programming, you need to understand more about how to create classes. OOP does not write classes about how to follow recommendations, principles, and patterns in OOP.
You should not create new objects inside another, you must specify the User object, its database object on which the User depends, using the constructor or the setter method. This is called dependency injection. The goal is to provide objects to the class they need using the constructor or setter method. And they must be implemented outside of this class, so itโs easier to set up the class. And when creating a class, you want it to be easy to see which dependencies this class has. Here you can read about the principle of control inversion: IoC
So your code will look like this:
<?php // User object that depends on Database object, and expects it in constructor. class User { protected $database; public function __construct($database) { $this->database = $database; } // -- SNIP -- } ?>
Now, to use this user class, you do this:
<?php $database = new Database($connParams); $user = new User($database); ?>
You can also use Injection Dependency with setter methods to set dependencies, but Il allows you to do this yourself :)
This is what I read about the principles of inversion of the Controll principle, as well as about containers for injecting dependencies and dependencies, these are the best ways to manage classes.
I saw a lot of PHP code, which is "OOP", and in fact they only use class classes as namespaces of features :) So, find out about the principles and patterns of OOP.
Good luck! :)
otporan
source share