Implementation of the Parent of All Models
Let's implement the parent class for all models:
<?php
namespace Core;
class Model
{
private $link;
public function __construct()
{
$this->link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
mysqli_query($this->link, "SET NAMES 'utf8'");
}
protected function findOne($query)
{
// there will be some code
}
protected function findMany($query)
{
// there will be some code
}
}
?>
As you can see, in the class constructor we are establishing a connection to the database. However, there is a problem: each created model (if there are several models within one controller action) will make its own connection to the database, and this is not optimal.
Let's make it so that the connection to the
database is created only for the first created
model, and the rest of the models use the already
created connection. To do this, let's make the
link property static:
<?php
namespace Core;
class Model
{
private static $link;
public function __construct()
{
if (!self::$link) { // if the property is not set, then we connect
self::$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
mysqli_query(self::$link, "SET NAMES 'utf8'");
}
}
protected function findOne($query)
{
}
protected function findMany($query)
{
}
}
?>
Copy the provided code of the Model class
and place it in the file /core/Model.php.
Implement the findOne method in this class.
Test its operation.
Implement the findMany method in this class.
Test its operation.