Hirazi Webtech

CodeIgniter Onboarding - Part 1 - Introduction to Objects

PHP Frameworks have always been in demand ever since the language has proved to be one of the best backend programming language available. Often people get confused while selecting an apt PHP framework for their project. Be it Symphony, Laravel, CodeIgniter or Slim (to name a few), it’s always a pickle to select one! At the very core of it, they all provide MVC architecture which enables the developer to get the benefits like Scalability and Robustness. If used properly, all the frameworks help the developers to get away from functional programming and open the doors for OOPs: Object Oriented Programming.

 

At Hirazi Webtech, we feel the selection of the framework is based on couple of factors:

 

  1. Complexity/Requirements of the project: What are you planning to achieve? What does your project demand from the environment? Are you looking to work with micro-services? Depending upon your requirements we weigh all the frameworks on various parameters. Please refer to the survey results by Sitepoint depicting the best PHP frameworks.
  2. Control over Projects: How much control you want on the project? Each framework comes with its baggage. The ability to understand how much of information is useful is the key here. All the frameworks have their standards and inbuilt libraries. The easier it is to understand and modify the inbuilt features, the simpler it becomes to achieve the end goal.

 

We use CodeIgniter for most of our projects as it gives us lot of control on how we want to customize the project. Clients usually have a need of customized admin panel which helps them track their data and generate reports. CodeIgniter gives a lot of control to meet these requirements. We thought we will share our approach with the community. This is a 4 part series explaining how you can setup your project in CodeIgniter to have full control over your projects.

 

Introduction to Objects

Every project at Hirazi Webtech starts with thinking about the Object Model. What are the entities involved? How they are connected and transact data with each other? Our database schema and object model go hand in hand. We create object layer in Codeigniter for each and every table in our database. Let’s understand this by an example:

 

Consider a table named “User” with fields id, name and email.

 

We will create a class called User under “root(project_name)/objects” directory to define the getters and setters for each column in the table.


<?php namespace Project_Name\Objects; defined('BASEPATH') OR exit('No direct script access allowed'); /** * Base class to represent a User */ class User { protected $user; /** * CI Singleton * @var object */ protected static $CI; public function __construct( $user ) { if( ! isset( self::$CI ) ) { self::$CI =& get_instance(); self::$CI->load->model( 'user_model' ); } $this->user = $user; } /** * Get the proper object based on its user ID * @param int */ public static function get_by_user_id( $user_id ) { if ( ! $user_id ) { return false; } if( ! isset( self::$CI ) ) { self::$CI =& get_instance(); self::$CI->load->model( 'user_model' ); } $user = self::$CI->user_model->get_user_by_id( $user_id ); return $user; } /** * Get the id for a user * * @return string */ public function get_id() { return $this->get_field( ‘id’ ); } /** * Get the name for a user * * @return string */ public function get_name() { return $this->get_field( ‘name’ ); } /** * Set the name for a user * * @return string */ public function set_name( $name ) { return $this->set_field( ‘name’, $name ); } /** * Get the email for a user * * @return string */ public function get_email() { return $this->get_field( ‘email’ ); } /** * Set the email for a user * * @return string */ public function set_email( $email ) { return $this->set_field( ‘email’, $email ); } /** * Get a field from the user object * * @param string $key * @return mixed */ protected function get_field( $key ) { $array = $this->user; return $array[ $key ]; } /** * Set a field for the user object * * @param string $key * @param mixed $value */ protected function set_field( $key, $value ) { self::$CI->user_model->update_user_field( array( $key => $value ), array( 'custId' => $this->get_id() ) ); $this->user[ $key ] = $value; } }

 

Now let’s understand what this class does:

 


namespace Project_Name\Objects;

Defines the namespace for this particular class. This helps us use the name “User” for other classes as well. Otherwise, we will have to suffix our class name like User_Obj or something. Namespacing prevents us from having unnecessary long names for classes.

 


protected $user;

Creating a “protected” user variable to store the object. Protected makes the object inheritable. This object eventually will store all the values of each and every column. Once this object is initialized, we can access the User table.

 


/** * CI Singleton * * @var object */ protected static $CI;

A protected static CodeIgniter global object is declared here which is initialized in the constructor function when a User object is being created. This object gives you access to CodeIgniter’s inbuilt function and is key in the foundation of this class.

 


public function __construct( $user ) { if( ! isset( self::$CI ) ) { self::$CI =& get_instance(); self::$CI->load->model( 'user_model' ); } $this->user = $user; }

This is the heart of the class as it is called when the object of this class is being initialized. But, more importantly it initializes CodeIgniter’s global object to load the user model (which will be explained in the next part of this series). There are two ways of creating a user object. One, by constructor,

 


$user = new User( $parameter );

This way of creating the object calls the constructor and accepts the $parameter and sets it to the protected $user object. The assumption here is: $parameter is the object returned from MySQL (explained in further parts of this series). Another way of creating objects is explained below.

 


/** * Get the proper object based on its user ID * * @param int */ public static function get_by_user_id( $user_id ) { if ( ! $user_id ) { return false; } if( ! isset( self::$CI ) ) { self::$CI =& get_instance(); self::$CI->load->model( 'user_model' ); } $user = self::$CI->user_model->get_user_by_id( $user_id ); return $user; }

If you have access to user_id and want to access its other properties, you can call

 


User::get_by_user_id( $user_id )

Which will again set the CI object if not set already (that’s why it’s kept static so as to be initialized only once). Then it calls the user_model method to get the user object. Models will be explained in the next part.

 


/** * Get the id for a user * * @return string */ public function get_id() { return $this->get_field( ‘id’ ); }

The heavy lifting for this class is done already. Not it’s time to set getters and setter for each column. Id being an exception as it usually will be the primary key so it doesn’t need any setter.

 


/** * Get the name for a user * * @return string */ public function get_name() { return $this->get_field( ‘name’ ); } /** * Set the name for a user * * @return string */ public function set_name( $name ) { return $this->set_field( ‘name’, $name ); }

These are usual fields/columns in our table which will need a getter and setter. Getters and setters use get_field and set_field (explained below) respectively to abstract the functionality.

 


/** * Get a field from the user object * * @param string $key * @return mixed */ protected function get_field( $key ) { $array = $this->user; return $array[ $key ]; } /** * Set a field for the user object * * @param string $key * @param mixed $value */ protected function set_field( $key, $value ) { self::$CI->user_model->update_user_field( array( $key => $value ), array( 'custId' => $this->get_id() ) ); $this->user[ $key ] = $value; }

These are the methods responsible for fetching and storing/updating the actual information from/in your tables. The protected $user object which stores all the information can be an array or an object depending upon developer’s preference of using MySQL queries in CodeIgniter. In this case it’s being returned as an array. get_field() receives a $key parameter which is the field (column) name of the user table.

 

set_field() receives two parameters, $key and $value, field to be updated and the new value. It uses user_model to update that field in the database and sets the new value in the protected user object as well.

 

That brings us to the end of our User object class. How is this class helpful? Anywhere in your controller, model or view, if you wish to display user information, you can use the User class to create the object and render data accordingly. Following are thebenefits of using this paradigm:

 

  • Once the object is created, you don’t need to worry about remembering the database column names
  • It gives you an abstracted layer for reusable methods.
  • Testing the class is very easy. You can easily write test cases for each getter and setter or other logical methods and use them anywhere in code.

 

I will share few examples of how to create User object:

  1. Say you are logging the user by verifying their username and password in your controller. After the verification is done the user_model will create a new User object and return it to the controller. (Detailed explanation coming in the next article)
  2. Getting the USER ID by any other table. Let’s assume you are generating a booking report. You query booking table and get the user_id for that booking. Now, all you need to do is:
  3. Import User class in your file:
  4. Call the static method to get the object: User::get_by_user_id( $user_id );
  5. Generating a report for all users. You will call a method to get all users in your model which will return an array of all the User objects.
  6. User is already logged in and their USER ID is saved in the cookie. When your controller loads, it makes a call similar to #2.

 

How to load these objects in CodeIgniter?

These objects are not automatically loaded in your application as they don’t exist in CodeIgniter. So, to make them work we will use libraries in CodeIgniter. Please take following step before adding objects in your project.

 

  1. Create a library: Custom_auto_loader.php under your libraries folder:

<?php class Custom_auto_loader{ public function __construct(){ spl_autoload_register( array( $this, 'loader' ) ); } public function loader( $className ) { $className = ltrim( $className, '\\' ); if ( 0 !== stripos( $className, 'Project_Name\\' ) ) { return; } $parts = explode( '\\', $className ); array_shift( $parts ); // Don't need "Project_Name\" $last = array_pop( $parts ); $last = $last . '.php'; $directory_path = strtolower( implode( $parts, '/' ) ); if( count( $parts ) > 0 ) { $file = APPPATH . 'inc/' . $directory_path . '/' . $last ; } else { $file = APPPATH . 'inc/' . $last ; } if ( file_exists( $file ) ) { require( $file ); } } }

This basically uses PHP’s spl_autoload_register function to load classes from the specified path. In my project it wasProject_Name/application/inc/objects.

 

  1. Include the custom_auto_loader in the config/autoload.phpas:

$autoload['libraries'] = array( 'custom_auto_loader' );

That’s it! You are all set!

 

This is the first part in the Onboarding series. Next, please go ahead and see the second part of the series: Working with Models.

 

Link to social platforms of Hirazi Webtech

We like to spread happiness. Let's do it together.

Contact details of Hirazi Webtech

Get in Touch

Would love to hear you over coffee!

Contact Detail

Hirazi Webtech

Mumbai, India

+91 96994-53388

contact.us@hirazi.com