Write a model for working with a database. RedBean PHP Examp... open

Write a model for working with a database. RedBean PHP Example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 7

For easy and safe work with the database we will use redbean.php. We can install it in our project using Composer. To do this, use the command:

composer require gabordemooij/redbean

We can also register this dependency manually by digging the composer.json file in the root directory of our project.

In composer.json we will add:

"require": {
    "gabordemooij/redbean": "^v5.6.1"
  }

Now let’s update our Composer by specifying the command:

composer update

Configuration file

Let’s create a configuration file in which there will be data for connection to DB.

return [
    'dsn' => 'mysql:host=localhost;dbname=testshop;charset=utf8',
    'user' => 'root',
    'password' => 'root'
]

Connection class

Now we can write a class of connection to a DB which will be in a core of our project (vendor/core/Db.php). That connection occurred only once we realize a pattern Sington

namespace core;
//namespace for RedBeanPHP
use RedBeanPHP\R;

class DB 
{
private static ?self $instance = null;

    private function __construct(){
        // connect our configuration file with data to connect to the database
        $db = require_once CONFIG . '/bdconfig.php';
        R::setup($db['dsn'], $db['user'], $db['password']);// RedBean method for connecting to the database
        if (!R::testConnection()) {//check our connection
            //if the connection failed, throw out an error
            throw new \Exception('Connection to DB failed', '500');
        }
        R::freeze(true);//freeze the creation of tables on the fly
        // If debugging mode is enabled in our application (DEBUG constant true or false)
        if (DEBUG) {
            //enable RedBean debugging and set its level 1
           R::debug(true, 1);
        }
    }

    public static function getInstance(): static
    {
        return static::$instance ?? static::$instance = new static();
    }
}

Create a base model class

namespace core;

abstract class Model
{

    public array $attributes = [];
    //fill in the error data
    public array $errors = [];
    //array of validation rules
    public array $rules = [];
    // field that has not been validated
    public array $labels = [];

    // in the constructor we call the static method getInstance of class Db to make its object (there the SingleTon pattern is implemented)
    public function __construct()
    {
        //connect to the database
        Db::getInstance();
    }

}

Now in our Controller class it is necessary to Call model, it is possible to make it by method getModel()

$controllerObject->getModel();

This method in the controller looks like this:

 //get our model
    public function getModel()
    {
        $model = 'app\models\\' . $this->route['admin_prefix'] . $this->route['controller'];
        //if a model exists, create a new instance of that model
        if (class_exists($model)) {
            $this->model = new $model();
        }
    }

Create a model for the home page

To do this, create a new Main.php class in the app/models directory.

namespace app\models;

use RedBeanPHP\R;

class Main extends \core\Model
{

    public function get_names(): array
    {
        //a RedBean method that retrieves data from a table
        return R::findAll('name');
    }

}

Now in the Controller we can receive data from a DB using model:

//let's turn to our controller
$names = $this->model->get_names();
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation