开发者

Strategy to instantiate classes in a PHP Project

开发者 https://www.devze.com 2023-02-08 01:59 出处:网络
I\'m building an application with a pattern that is something like the MVC and I need to know how to deal with a specific situation. I will explain visualy.

I'm building an application with a pattern that is something like the MVC and I need to know how to deal with a specific situation. I will explain visualy.

I have the project folder this kind of organization:

+ database
  |
  - postgresql.php
+ models
  |
  - categories.php
  - countries.php
  - domains.php
- example_usage.php

Ok, in the database/postgresql.php I have the Driver for the PostgreSQL Database, with the code bellow:

<?php

    // Just to test the Class
    // Parse Config.ini - Parsing do ficheiro de Configuração
    $ini_array = parse_ini_file("../Config.ini", true);

    // Mostra a BD configurada para funcionar
    $active_database = $ini_array['current_database'];

    // Mostra os dados da BD configurada para funcionar
    $details_active_database = $ini_array[$active_database];

    // Instanciar a Base de Dados
    $db = new Postgresql(
        $details_active_database['host'], $details_active_database['port'], 
        $details_active_database['user'], $details_active_database['password'], 
        $details_active_database['dbname']
    );

    print_r( $db->query('select * from tdir_categorias') );


class Postgresql {

    private $connection;

    public function __construct($hostname, $port, $username, $password, $database) {

        // Lançar excepções para os parametros
            // hostname nulo ou branco
            if (is_null($hostname) OR $hostname == '') {
                // O $hostname não pode vir a vazio, vou lançar excepção
                throw new Exception("O parametro hostname nao pode vir a vazio, Metodo em causa: __construct()");           
            }
            // port nulo ou branco
            if (is_null($port) OR $port == '') {
                // O $port não pode vir a vazio, vou lançar excepção
                throw new Exception("O parametro port nao pode vir a vazio, Metodo em causa: __construct()");           
            }
            // username nulo ou branco
            if (is_null($username) OR $username == '') {
                // O $username não pode vir a vazio, vou lançar excepção
                throw new Exception("O parametro username nao pode vir a vazio, Metodo em causa: __construct()");           
            }   
            // password nulo ou branco
            if (is_null($password) OR $password == '') {
                // O $password não pode vir a vazio, vou lançar excepção
                throw new Exception("O parametro password nao pode vir a vazio, Metodo em causa: __construct()");           
          开发者_如何学Go  }
            // database nulo ou branco
            if (is_null($database) OR $database == '') {
                // O $database não pode vir a vazio, vou lançar excepção
                throw new Exception("O parametro database nao pode vir a vazio, Metodo em causa: __construct()");           
            }                           

        // Connection String
        $connection_string = "host=$hostname port=$port dbname=$database user=$username password=$password";

        // Connect to Database
        if (!$this->connection = pg_connect($connection_string)) {
            throw new Exception("Nao foi efectuada com sucesso ligacao a Base de Dados, Metodo em causa: __construct()");
        }
    }

    public function query($sql) {

        $resource = pg_query($this->connection, $sql);

        // Se $resource for TRUE
        if ($resource) {
            if (is_resource($resource)) {
                $i = 0;

                $data = array();

                while ($result = pg_fetch_assoc($resource)) {
                    $data[$i] = $result;

                    $i++;
                }

                pg_free_result($resource);

                $query = new stdClass();
                $query->row = isset($data[0]) ? $data[0] : array();
                $query->rows = $data;
                $query->num_rows = $i;

                unset($data);

                return $query;  
            } else {
                return TRUE;
            }
        } else /* Se $resource for FALSE */ {

            throw new Exception(pg_last_error($this->connection) . " SQL, " . $sql . ": query()");
        }
    }

    public function escape($value) {

    }

    public function countAffected() {

    }

    public function getLastId() {

    }

    public function __destruct() {

    }
}

?>

In the models files I don't have nothing yeat.

<?php

class Categories {

    // do things with the database calling the postgresql.php driver.
}

?>

And the file "example_usage.php" will be the file that I want to call the models, this file is a kind of controller in the MVC Pattern.

My doubt... How can Instantiate the Postgresql.php Class and the Models Classes to call the methods inside the Models Classes in the example_usage.php

Please give me a clue. I would be very aprreciated.

Sorry for my bad english.

Best Regards,


You simply need to include the files in the script:

//example_usage.php
include 'database/postgresql.php';
include 'models/categories.php';

$db = new Postgresql($hostname, $port, $username, $password, $database);
$categories = new Categories();

etc...

This will take you so far... eventually you will want to take a look at autoloading your classes. I recommend reading first about the __autoload() function, and then about spl_autoload() and it's related functions.

Aside

So far you've only covered the M in MVC. Typically a web MVC will use a "front controller" to dispatch requests. All requests get passed to the front controller. That front controller will instantiate a specific controller for the request, which will talk to the model, and then load a view class that has all of your HTML in a template. Finally, that will view be responded to the browser.

Using Dependency Injection

You mentioned that you wanted to instantiate the Postgresql class in the model. Dependency Injection (DI) is the easiest way to do this, and is the smartest way to ease unit testing of your models. Here is an example:

class Categories {

    private $db_driver;

    public function __construct($driver = NULL) {
        if (empty($driver)) {
            include_once 'path/to/postgresql.php';
            $driver = new Postgresql(
                $hostname, $port, $username,
                $password, $database
            );
        }
        $this->db_driver = $driver;
    }
}

Again, I'm using include to illustrate how to get the class files, and again I recommend just using an autoload function in actual production. Obviously the above is just an illustration, so you would need to fill in the Postgresql constructor variables with your defaults.

With the above code you can do the following:

//example_usage.php
include_once 'models/categories.php';
$categories = new Categories();

Or you can do this:

//example_usage.php
include_once 'database/postgresql.php';
include_once 'models/categories.php';
$db_driver = new Postgresql($hostname, $port, $username, $password, $database);
$categories = new Categories($db_driver);

Using DI will allow you to pass a Mock database class to the model.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号