Showing posts with label codeigniter. Show all posts
Showing posts with label codeigniter. Show all posts

Tuesday, April 28, 2015

CodeIgniter Tip: Accessing CodeIgniter Instance Outside

Sometimes you need to access CodeIgniter application instance completely outside of it, may be in Ajax request or an script which is not part of your main CI application. To do so, you can do this:

// file: CI.php
ob_start();
require_once 'index.php'; // adjust path accordingly
ob_get_clean();
return $CI;

Here we are including index.php file of main CI application. We are using buffering functions here so we don't see actual CI application page and finally we we return the $CI instance so that in any page where we need CI instance, we can simply include this file there. So to use it in some other script, you would simply include above file there:

$CI = require_once 'CI.php';
echo $CI->config->item('base_url'); // test CI instance

That should work for the most cases.

I happen to need CI instance in a cli/console application but above method didn't do the trick for me in console app. So here is another very very hacky way of getting instance of CI in a console app that I was able to come up with after analyzing CodeIgniter code:

// Hacky Way of Accessing CI Instance Outside

error_reporting(1);

$environment = 'development';

$system_path = 'system';

$application_folder = 'application';

if (realpath($system_path) !== false) {
    $system_path = realpath($system_path) . '/';
}

$system_path = rtrim($system_path, '/') . '/';

define('BASEPATH', str_replace("\\", "/", $system_path));
define('APPPATH', $application_folder . '/');
define('EXT', '.php');
define('ENVIRONMENT', $environment ? $environment : 'development');

require(BASEPATH .'core/Common.php');

if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/constants.php')) {
    require(APPPATH.'config/'.ENVIRONMENT.'/constants.php');
} else {
    require(APPPATH.'config/constants.php');
}

$GLOBALS['CFG'] =& load_class('Config', 'core');
$GLOBALS['UNI'] =& load_class('Utf8', 'core');

if (file_exists($basepath.'core/Security.php')) {
  $GLOBALS['SEC'] =& load_class('Security', 'core');
}

load_class('Loader', 'core');
load_class('Router', 'core');
load_class('Input', 'core');
load_class('Lang', 'core');

require(BASEPATH . 'core/Controller.php');

function &get_instance() {
    return CI_Controller::get_instance();
}

$class = 'CI_Controller';
$instance = new $class();

return $instance;

As said above, this is extremely hacky way and may or may not work in all cases and you would also need to adjust paths in above code and/or load more libraries/helpers/etc you need by modifying it.

Friday, April 24, 2015

Database Migrations in CodeIgniter

What is Migration ?

Quoting from CI documentation:

Migrations are a convenient way for you to alter your database in a structured and organized manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run them. You’d also have to keep track of which changes need to be run against the production machines next time you deploy.

Migrations come in extremely handy when you are working with a team of developers. Normally whenever you created a new database table or modified existing one by adding/removing certain fields or even added some data to database, you would tell your fellow developers to run those SQL queries in their machines so that database remains in sync.

This isn't ideal, we needed some way so that:

  • Framework (CodeIgniter or whatever) automatically detects and runs those SQL queries on our behalf without handing over SQL query files to other developers each time we make some change to database

  • And keeps versions of our database changes similar to versioning of files when we use git. This means we can go back and forth easily to specific version of database changes. Something went wrong on production site and you need to revert to specific database change, no problem simply tell CodeIgniter which change to revert to and you are done.

That's what migrations do.

You now see how important and useful migrations are. One of the first frameworks that really shined up with this idea was Laravel and then I saw similar concept in Android applications. CodeIgniter also allows us to setup migrations which is really cool.


Setting Up Migrations in CodeIgniter

In order to enable migrations:

  • Open application/config/migration.php file and set the value for $config['migration_enabled'] from false to true.
  • Create a folder called migrations in application/config/ folder and that's it.

In migrations folder, we can create our database changes. Let's say we want to create a new users table. To do so, create a file called 001_add_users.php in migrations folder and paste this code in it:

class Migration_Add_user extends CI_Migration
{
    public function up()
    {
        $this->dbforge->add_field(
           array(
              'id' => array(
                 'type' => 'INT',
                 'constraint' => 5,
                 'unsigned' => true,
                 'auto_increment' => true
              ),
              'name' => array(
                 'type' => 'VARCHAR',
                 'constraint' => '100',
              ),
              'email' => array(
                 'type' => 'TEXT',
                 'null' => true,
              ),
           )
        );

        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('users');
    }

    public function down()
    {
        $this->dbforge->drop_table('users');
    }
}

There are few things to notice:

  • We see that this migration class extends CI_Migration class.
  • It has only two methods up() and down()
  • It uses dbforge object to build up queries in OOP way
  • The migration files should be prefixed with three digits like 001_first_migration.php, 002_second_migration.php and so on

So that's how a typical migration class should look like. But we are only interested in up() and down() methods. The up() method is called by system whenever you need to update the database and down() method is used to revert that change that was done by the up() method. For example, if in up() method you create a new table then in down() method you should specify code to remove that table. Similarly if in up() method you add a new field to some table then in down() method you should specify code that deletes that field. So both of these methods are opposite to each other. In each migration you should always specify the code for both.

Now that we have created our migration, we need to run it. Let's create a controller called Migrate that will run our migrations:

class migrate extends CI_Controller {
    public function index()
    {
        // load migration library
        $this->load->library('migration');

        if ( ! $this->migration->current())
        {
            echo 'Error' . $this->migration->error_string();
        } else {
            echo 'Migrations ran successfully!'
        }   
    }    
}

Now if you visit your application url at http://yoursite.com/migrate and all goes well, you should success message and the new table users should be created in the database. If you run migration for the first time, you would also notice that a table called migrations should also be created in your database by CodeIgniter. This table can keep track of your database migration changes.

Now refresh page or re-visit http://yoursite.com/migrate and you would notice nothing happens, this time CodeIgniter won't do anything with your migration since it has already been run. To prove it further, delete users table manually from your database and then re-visit http://yoursite.com/migrate page and you will see CodeIgniter didn't create users table again. That's because CodeIgniter knows that it has already run that particular migration. Now if you add some other migrations in migrations folder and then visit migrate URL again, this time CodeIgniter will run your new migrations. How does CodeIgniter know which migrations to run ? It keeps track of them migrations table that it creates as well as config['migration_version'] setting in application/config/migration.php file. That's how CodeIgniter versions your database changes.

You see how simple and powerful migrations are. Now that you have made changes to database, you don't need to worry how other team members will embrace those changes, all you need to ask them is to visit the migration url and database on their machines will also get those changes!

In the above example, we used $this->migration->current() method to go to current migration version that is set in config['migration_version']. There are couple of more methods that allow you to migrate based on most recent version of migration based on file system and one that allows you to go to specific migration version. To lean more about dbforge methods, check out its documentation.

So if you have never used database migrations before, you should definitely use them because they are awesome!

Thursday, April 23, 2015

Development Environments in CodeIgniter

What is Development Environment?

The environment may be development, staging, production or some other. Each environment can have different set of settings; for example different application configurations, database settings, email settings, logging, error reporting levels and more. By using different environments for your application, you can actually ease things up for yourself when deploying as you won't have to change configurations, database setting and error reporting levels after application is moved to development or production site. Once you setup different development environments, the system would automatically know your application-wide settings to use.

If you have worked with Laravel, you would notice that you can setup different development environments for your application by specifying your current development environment in the .env file. You can actually have different development environments in CodeIgniter as well.

If you open up index.php file of CodeIgniter, you would notice it sets development environment as default in a constant ENVIRONMENT:

CodeIgniter 2+:

define('ENVIRONMENT', 'development');

CodeIgniter 3+:

define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');

And later in the very file, CI sets up error reporting based on that environment:

if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;

        case 'production':
            error_reporting(0);
            break;

        default:
            exit('The application environment is not set correctly.');
    }
}

In fact, CI uses ENVIRONMENT constant at quite some places, quoting from its documentation:

There are some places in the CodeIgniter system where the ENVIRONMENT constant is used.


Setting Different Development Environments

Let's say we want to have ability to have different development environment for local, development and production. For example, we want to be able to:

  • Have error reporting turned on local and development environments but turned off on production
  • Have logging turned on local and development environments but turned off on production
  • Have different config settings for each of local, development and production environments
  • Have different database settings for each of local, development and production environments
  • Have different email settings for each of local, development and production environments

According to CI documentation, in order to setup different environments, you need to create a folder inside application/config folder matching the name of environment. For example, to create development environment, we would create a folder application/config/development.

So create three folders named development, local and production inside application/config folder. And copy config.php, database.php and email.php from application/config to three folders you just created. If email.php doesn't exist, you can create one.

Now each of your config.php, database.php and email.php can have differnt settings. CodeIgniter will automatically choose right files to use based on your current environment. For example in application/config/local/config.php and application/config/development/config.php files, you can enable error reporting and logging using $config['log_threshold'] setting by setting it to 1 but disable error reporting and logging in production environment by setting $config['log_threshold'] to 0 in application/config/production/config.php file. Similarly, you can now easily setup different $config['base_url'] in each of your environments' config.php file like:

application/config/local/config.php:

$config['base_url'] = 'http://localhost/mysite';

application/config/development/config.php:

$config['base_url'] = 'http://mysite.com/development';

application/config/production/config.php:

$config['base_url'] = 'http://mysite.com';

Now when you upload your application, all you have to do is specify which environment you want to use by editing index.php file:

define('ENVIRONMENT', 'production'); 

If you upload your application to production site, set it to production or if you upload it to development,set it to development.

I am sure you don't want to specify your environment for ENVIRONMENT each time you upload/deploy your application, here is how you can do so:

$local_servers = array('localhost');
$isLocal = in_array($_SERVER['SERVER_NAME'], $local_servers);

if ($isLocal) {
    $env = 'local';
} else {
    // check development word in url
    preg_match('#/development#', $_SERVER['REQUEST_URI'], $isDevelopment);

    $env = $isDevelopment ? 'development' : 'production';
}

And then use $env variable:

define('ENVIRONMENT', $env);


Wednesday, April 22, 2015

Controllers for Frontend and Backend in CodeIgniter

I find it very inconvenient when you need to create all frontend and backend controllers without having any common functionality. I don't like the face that I always have to extend CI_Controller for all my backend and frontend controllers. I need ability to specify which controllers are related to frontend and which ones relate to backend .

So instead of doing this:

class someFrontendController extends CI_Controller {}
class someBackendController extends CI_Controller {}

I should be able to do this:

class someFrontendController extends FrontendController {}
class someBackendController extends BackendController {}

I also need ability to specify common controllers that can be applicable to both frontend and backend:

class someCommonController extends CommonController {}

I will explain benefits of having such controllers below. But for now, how do we do that ? Well CodeIgniter is very flexible and does allow you to achieve just that.

Extending CodeIgniter's CI_Controller Class

In order to have separate controllers for backend, frontend and common controllers, please follow these steps:

1) Make sure that config $config['subclass_prefix'] is set to MY_ in application/config.php file. It should be so by default.

2) Create a file called MY_Controller.php in application/core folder and paste this code in it:

<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class CommonController extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }
}

class FrontendController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
    }
}

class BackendController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
    }
}

Now for all of your controllers that belong to frontend, you would extend FrontendController instead of CI_Controller and for all of your controllers that belong to backend, you would extend BackendController instead of CI_Controller like I mentioned above:

class someFrontendController extends FrontendController {}
class someBackendController extends BackendController {}

And for any controllers that might share common data for frontend and backend, you would extend CommonController:

class someCommonController extends CommonController {}

What's the Point ?

You might already have guessed the benefits of having separate controllers but if you haven't yet, well here they are:

  • You can now easily distinguish which controllers belong to backend and which ones belong to frontend
  • You now have ability to have common code for both sides of an application.

By common code, I mean any functionality that you would want to be shared in all of your controllers. Let's assume that we have created login functionality and user is logged on frontend. Now normally you would write some code in all of your controllers (for authorized pages for example) that would check whether or not user is logged in; if user is not logged in, redirect him back to login page something like:

class MyController extends CI_Controller
{
    public function index() {
        // check if user is logged in
        $this->checkLoginStatus();

        // more code of controller when user is logged in
    }

    // redirect user to login page if not logged in
    protected function checkLoginStatus() {
        if (! $this->session->userdata('is_logged_in')) {
            redirect('login');
        }
    }
}

Now for all of your pages that can be viewed only when user is logged in, you will need to insert checkLoginStatus() function in all of those controllers and then call it index() function. That's not good, it is repeating code. Remember the rules Don't Repeat Yourself (DRY) and Keep It Simple, Stupid! (KISS) :)

Let's KISS it; simply put checkLoginStatus() function code in your FrontendController and now all controllers that extend it will have this login check functionality:

class FrontendController extends CommonController
{
    public function __construct()
    {
        parent::__construct();

        // check if user is logged in
        $this->checkLoginStatus();
    }

    // redirect user to login page if not logged in
    protected function checkLoginStatus() {
        if (! $this->session->userdata('is_logged_in')) {
            redirect('login');
        }
    }    
}

And now you don't need to do anything in your normal frontend controllers. You now get login check functionality out of box. In the similar fashion, you can have some common functionality for all of your backend controllers by putting some code in BackendController. This was just an example for login check but of course you could have some other requirement that you wanted to inject in all of your controllers by using FrontendController or BackendController.

You might ask, you could have done all of this by may be using CI Hooks or may be traits, well that's true but I believe having separate controllers gives you more control and separation of concerns.

Similarly, you could put whatever code you want in class for CommonController that would be applicable to both frontend and backend. For example you could setup application's overall configuration, upload paths, logos, etc whatever you think should be available site-wide; in all controllers of backend and frontend.

So anything that you put in FrontendController will be available in all controllers of frontend that extend it. Anything that you put in BackendController will be available in all controllers of backend that extend it. Anything that you put in CommonController will be available in all controllers of frontend + backend.


And finally there is one more problem I don't like personally. Even though we can now easily find out which controllers belong to frontend or backend, we still have to put all of them in application/controllers folder. This doesn't easily tell by looking at file names which controllers belong where unless you open it up and see what it extends. Of course we could use prefix for controller file names like front-foo-controller.php or backend-bar-controller.php but still you have to put them in same folder. It would have been cool if you could have folder structure like this where you can go any nested level while having each distinct part of functionality in its own module:

+ frontend
   + module-one
      + controllers
          - controllers-one.php
          - controllers-two.php
      + models
          - model-one.php
          - model-two.php
      + views
          - view-one.php
          - view-two.php
   + module-two
   + module-three
+ backend
   + module-one
   + module-two
   + module-three

Oh yes you can do that as well with the help of HMVC module for CodeIgniter :)

Note: HMVC is not just about organizing folders, it is whole concept where you get ability to have one controller call some other controller. In HMVC, Each model-view-controller triad represents distinct piece of functionality or mini application which runs independent from other triads.

Have fun!

Popular Posts