phpoopphp-mysqlidb

Constructing a site with classes


Recently I started looking more seriously into classes and OOP in general in PHP. I'm trying to create a simple site while taking advantage of classes as much as possible but there have been some questions that have been stuck in my mind.

More specifically I'd like to know how would a 'proper' site structure look like with classes and methods that deal with users, pages, menus, etc. Currently I'm using this wrapper to get around MySQLi more effectively and I can't seem to decide how should I implement this wrapper with other objects - do I create a new class for users, menus, etc. separately and just pass the database variable through the class every time I create an instance?

$db = new Mysqlidb (DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
$user = new User ($db);

Or do I just extend the SQL class as "models" like the wrapper's author has pointed out here.

Also in general, what should remain a class, what should I handle with only functions? How should I handle things with my MySQL class?

Is it a good practice to handle every single menu item/user/page as an object?

These are just some of the things confusing my mind right now. There are quite a few examples on the web about OOP but I still haven't found a decent one to explain the questions I asked above.


Solution

  • if you already familar with mysqlidb, its 2.1 and 2.2 releases are coming with a new dbObject class to implement models with some extra features.

    Check out their https://github.com/avbdr/PHP-MySQLi-Database-Class/blob/master/dbObject.md

    If you still want to stick with a pure MysqliDb classes you can try to do:

    class Model {
        protected $db;
    
        public function __constuct () {
            $this->db = MysqliDb::getInstance();
        }
        public function __call ($method, $arg) {
            call_user_func_array (array ($this->db, $method), $arg);
            return $this;
        }
    }
    
    class user extends Model {
        $this->tbl = 'users';
        public function create ($data) {
             $this->db->insert (...);
        }
        public function admins () {
             return $db->where ("role", "admin")->get($this->tbl);
        }
    }
    

    This will give you models like:

    $user = new user ();
    $q = $user->where('login','root')->admins();
    

    Take a look at dbObject as its pretty simple and I bet it will do a job you need it to do.

    As for OOP I would avoid storage of the mostly static content in the database. Just split menus/sidebars/header/etc into separate subviews and you should be fine.