Tuesday, 28 August 2018

The PHP OOP load does not return the correct object

Problem: When I load model with load object, it will NOT return second model.

Take a look at class Test where I load model with load object. Code $this->two will return object One ( should load object Two ).
Q: How to solve this problem? I am open your suggestions/ideas/code
Current Result:
one is working
object(One)#3 (1) { ["error":"Model":private]=> NULL }
one is working
object(One)#4 (1) { ["error":"Model":private]=> NULL }

Correct result:
one is working
object(One)#3 (1) { ["error":"Model":private]=> NULL }
two is working
object(Two)#4 (1) { ["error":"Model":private]=> NULL }

PHP:
one_model.php
<?php

class One extends Model {

    public function test() {
        echo '<p>one is working</p>';
    }

}

two_model.php
<?php

class Two extends Model {

    public function test() {
        echo '<p>two is working</p>';
    }

}

index.php
<?php

class Controller {

    public $load;

    public function __construct() {
        $this->load = new Load();
    }

}

class Load {

    public function model($name) {
        if (!class_exists($name)) {
            require(strtolower($name) . '_model.php');
        }
        $model = new $name;
        return $model;
    }

}

class Model extends PDO {

    private $error;

    public function __construct() {

        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );

        try {
            $dsn = "mysql:dbname=test;host=localhost;charset=utf8";
            parent::__construct($dsn, 'root', '', $options);
        }
        catch (PDOException $e) {
            $this->error = $e->getMessage();
        }
    }

}

class Test extends Controller {

    public $one;
    public $two;

    public function __construct() {
        parent::__construct();

        $this->one = $this->load->model('one');
        $this->two = $this->load->model('two');
    }

    public function testing() {
        $this->one->test();
        var_dump($this->one);
        $this->two->test();
        var_dump($this->two);
    }

}

// Usage
$test = new Test();
$test->testing();


I moved PDO wrapper from Model to separate class and create object for database connection.
Is this good approach ? Is this "waste of resources"?
class Database extends PDO {

    private $error;

    public function __construct() {

        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );

        try {
            $dsn = "mysql:dbname=test;host=localhost;charset=utf8";
            parent::__construct($dsn, 'root', '', $options);
        }
        catch (PDOException $e) {
            $this->error = $e->getMessage();
        }
    }

}

class Model {

    public $db;

    public function __construct() {
        $this->db = new Database();
    }

}

0 comments:

Post a Comment