Jump to content

PHP5 - Creating a single instance for an entire application?


Recommended Posts

Hi,

 

I am trying to write a small MVC framework. I am having a little trouble setting something up. I want to have a single instance for the entire application.

 

For example.

 

The instance would contain the following.

$this->db

$this->session

$this->validation

 

These should be accessible to all classes should they try to access them.

 

I have heard about magic __get() __set() methods but don't quite understand how they work or if they would help. Does anyone know how I can achieve this?

 

If __get() __set() methods can be used could someone briefly explain how.

 

Thanks

Thanks, that sounds like it would work. So am I right in thinking that I would do something like this...

 

class instance {

}

 

Then something like this.

 

class controller {
  public function __construct($instance) {
    $this->i = $instance;
  }
}

 

class c extends controller {
  public function __construct() {
    $this->i->db = $this->load->library('db');
    $this->i->auth = $this->load->library('db');
    $this->i->session = $this->load->library('db');
  }
}

 

This actually wouldn't require much modification to adapt what I have at the moment. Have I interpreted this correctly?

Everything you specify in your controller (db, auth, session) is actually just a model and these may be present in the controller. I actually do not recommend adding your db directly into your controllers as your controller does not need to know that your application uses a database nor that it uses sessions. You can hide these behind a new model layer for example:

 

$user = UserRepository::findByUsername(..);

 

Uses a database to find the username but it actually does not know if this database is mysql, a flat file or sqlite or something..

 

Same applies for auth:

 

AuthService::logon($this->getRequest());

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.