phpcodeigniterconstantsclass-constants

Redefining Codeigniter slug-based constants in the model per user


I have a Content Management System, where slug-based constants for each logged-in user's appropriate directories are defined for one or all controllers within the model. I happen to stumble upon this find by experimenting with redefining constants per logged-in user.

I did not think redefining constants was possible, but I think I am not understanding how Codeigniter or PHP is able to redefine constants in this fashion. I do not receive any PHP error stating that it was unable to redefine constants, so has me to believe that the model or controller instance is unset for each controller?

Controller:

class Content extends CI_Controller {
    function __construct()
    {
        parent::__construct();
        $this->load->model('main_model');

        ...
            get slug from logged_in user
        ...

        $this->main->set_slug_based_constants($slug)
    }
}

One main model (I know it's bad to do this):

class Main_model extends CI_Model{

    public function set_slug_based_constants($slug)
    {
        define('CLOUDFRONT_DIRECTORY', $slug.'_cloudfront_directory');
    }
}

From Codeigniter Docs: Dynamic Instantiation. In CodeIgniter, components are loaded and routines executed only when requested, rather than globally.

So I would like to believe that my assumption is correct in this case based on the Codeigniter Docs.


Solution

  • It not so much "unset" as "not yet defined". Each browser request to a URL (controller) is a unique process in the server. So the constant is not redefined but is newly instantiated for each URL request.

    If you try to run $this->main_model->set_slug_based_constants($slug); a second time you will get a PHP error message stating that Constant CLOUDFRONT_DIRECTORY already defined.

    Try this version of the controller to see the error.

    class Content extends CI_Controller
    {
        function __construct()
        {
            parent::__construct();
            $this->load->model('main_model');
            $this->main_model->set_slug_based_constants("Dave");
        }
    
        function index()
        {
            echo "The constant's value is <strong>".CLOUDFRONT_DIRECTORY."</strong><br>";
            $this->main_model->set_slug_based_constants("jruser");
            echo "The constant's value is  <strong>".CLOUDFRONT_DIRECTORY."</strong><br>";;
        }
    
    }
    

    It will produce output something like this.

    The constant's value is Dave_cloudfront_directory

    A PHP Error was encountered

    Severity: Notice

    Message: Constant CLOUDFRONT_DIRECTORY already defined

    Filename: models/Main_model.php

    Line Number: 13

    The constant's value is Dave_cloudfront_directory