Skip to main content

PHP Chaining Function

PHP 4 - 7, Offers Chaining Function With Slight Differences, but this Post and Example Focuses on PHP 7's.

Study the Example Below, Take note of the Power Array, Contatenation and Conditional Statements Have

<?php
class DBManager
{
    private $selectables = array();
    private $table;
    private $whereClause;
    private $orderClause;
    private $limit;

    public function select() {
        $this->selectables = func_get_args();
        return $this;
    }

    public function from($table) {
        $this->table = $table;
        return $this;
    }

    public function where($where) {
        $this->whereClause = $where;
        return $this;
    }

    public function order($type) {
        $this->orderClause = strtoupper($type);
        return $this;
    }

    public function limit($limit) {
        $this->limit = $limit;
        return $this;
    }

    public function result() {
        $query[] = "SELECT";
        // if the selectables array is empty, select all
        if (empty($this->selectables)) {
            $query[] = "*";  
        }
        // else select according to selectables
        else {
            $query[] = join(', ', $this->selectables);
        }

        $query[] = "FROM";
        $query[] = $this->table;

        if (!empty($this->whereClause)) {
            $query[] = "WHERE";
            $query[] = $this->whereClause;
        }

        if (!empty($this->orderClause)) {
            $query[] = "ORDER BY ID";
            $query[] = $this->orderClause;
        }

        if (!empty($this->limit)) {
            $query[] = "LIMIT";
            $query[] = $this->limit;
        }

        return join(' ', $query);
    }
}

$db = new DBManager();

$db->select()->from('userTable')->where(user = 1)->limit(10)->result();
// SELECT * FROM userTable WHERE user = 1 LIMIT 10;

Comments

Popular posts from this blog

How to Connect To Your Database Using PHP and MySQLi

Connecting your project to SQL Database comes with these 3 requirements. 1. Create 2 Pages (Optional tho' but safe) with these names: config.php connect.php Reasons, If A hacker, hacks to your connect page, he'll get all there is to know about your script and your database and that might be really harmful but if, there's a configuration with secret details and a connection with configured details separately created there's actually a sense of safety. In the first  config.php Type these codes <?php  define("DATABASE_HOST","localhost"); define("DATABASE_USER","root"); define("DATABASE_NAME","test_name"); define("DATABASE_CODE","");  ?>   DATABASE_HOST This Database_host is by default a "localhost" since it is a test work done locally, using *AMP (APACHE,  MYSQL, & PHP). DATABASE_USER   The database user is by default "root" but can be alt