views:

33

answers:

3

Hello again, after reading the responses I have rewritten my question.

Let's say I have a theoretical php application that uses objects that do different things. For every page that gets loaded by the application, different scripts will be run.

now I made a simple php script that creates a simple object. (this is all made up, I'm just trying to understand this before I code it)

$user = new userClass($db);
$user->login($credentials);

all is fine, and I can even repeat the procedure several times after creating the user class

$user = new userClass($db);
$user->login($credentials);
...
$user->login($credentials2);

now imagine if these 2 parts are split in 2 different php files.

file1:
$user = new userClass($db);
$user->login($credentials);
file2:
$user->login($credentials2);

include file1
include file2

if they are run in order all is fine, but if they are not, or if file1 is not included at all...

file2:
$user->login($credentials);
file1:
$user = new userClass($db);
$user->login($credentials2);

include file2
include file1

then it won't work... they have to maintain order, so lets make a main php file that gets loaded no matter what.

main file:
$user = new userClass($db);
file1:
$user->login($credentials);
file2:
$user->login($credentials2);

(included files with autoloading for example) include main include file1 include file2 or include main include file2 include file1 or include main include file2

now file1 and 2 can be loaded in any order, and one does not depend on the other, but what if both file1 or file2 are unnecessary?

main file:
$user = new userClass($db);
//nothing else gets loaded

then the main file is also unnecessary, and will prove to be a resource hog, sure if its one class it's no problem, but what if the main file loads hundreds of classes that never get used?

not elegant at all.

Then let's try to do it another way, let's scrap the main file completely and do it like this (below is the bare bone example of what I want to achieve):

file1:
if(!is_object($user)){
    $user = new userClass($db);
}
$user->login($credentials);
file2:
if(!is_object($user)){
    $user = new userClass($db);
}
$user->login($credentials2);

sure, it works, but it's not elegant, now is it?

let's try it with method overloading...

class loader {
   private $objects;
   private $db;
   function __construct($db){
      $this->objects = array();
      $this->db = $db;
   }
   function __get($name){
      if(!isset($this->objects[$name])){
         return $this->objects[$name] = new $name($this->db);
      }
   }
}

main file:
$loader = new loader($db);
file1:
$loader->user->login($credentials);
file3:
$loader->user->login($credentials3);
file2:
$loader->user->login($credentials2);
file4:
$loader->user->login($credentials4);

seems to work, until you realize that you can no longer give any of the objects that are created this way any other variable except $db. This means that loader class is limited to use with user class only (for example) because using loader class with any other class will require editing of the loader class

and a simple script like this:

$user = new userClass($this->db);
$user->login($credentials);
$form = new formClass($_POST);
$form->process($info);

will require 2 separate loader classes or at least 2 methods in the loader class

   class loader {
       private $objects;
       private $db;
       function __construct($db){
          $this->objects = array();
          $this->db = $db;
       }
       function getuserclass($name){
          if(!isset($this->objects[$name])){
             return $this->objects[$name] = new $name($this->db);
          }
       }
       function getformclass($name){
          if(!isset($this->objects[$name])){
             return $this->objects[$name] = new $name($_POST);//just an unrealistic example.
          }
       }
    }

main file:
$loader = new loader($db);
file1:
$loader->getuserclass('user')->login($credentials);
file3:
$loader->getformclass('form')->process($info);

but this is not elegant either.

How is this really supposed to be done?

+1  A: 

This would probably work for you:

class loader {
   private $objects;

   function __construct(){
      $this->objects = array();
   }

   function __call($name, $args){
      if(!isset($this->objects[$name])){
         return $this->objects[$name] = new $name($args);
      }
   }
}
$loader = new loader();

$user = $loader->user($db);
$form = $loader->form($form_args);

If you want multiple instances you could perhaps include an additional first argument in each call to loader that is a name, and change the loader code to use the first arg as a key for the object, and pass the rest to the object's constructor.

Finbarr
so your suggesting i do it like in the semi-last example but with singletons? that's not really the problem im trying to describe.I need to know where I need to put the loading options to load a single instance of a object or multiple objects.
YuriKolovsky
That's really a design choice. There's no single right way of doing it. If you really want to overengineer it, you could, for example, pass the loader class a strategy object that contains the logic for how requests for objects should be handled.
Finbarr
I have edited my answer to try and solve the *problem* you describe.
Finbarr
A: 

imo, this is exactly why using include() through an app is a bad idea, and can create serious maintenance headaches. Especially for people who are unfamiliar with the code. They may open a PHP file two years from now and see a variable... and have no idea what it is or where it is initialized.

If you are encountering this sort of problem, your app's basic structure probably needs to be redone. a better way to organize your app is to put all includes at the top of your app, so that there's no ambiguity about what files are included, or the order that they are included. And then use a templating system to control output. Dont use 'includes()' to insert code inline. Use them instead more like C includes. Your included files should house functions and classes, and very little, if any code, that runs in the global scope.

Do that, and I think you'd find that you'll stop encountering these sort of problems.

GrandmasterB
yes, that is already the case, each include houses one class, and one class only, above is just a theoretical example portraying the problem with a large app that does not need all it's code to show one simple page, but might need half its code to show another page.
YuriKolovsky
Its when you start using includes in multiple files that the problem you are seeing starts to occur. Its all about the structure of the app. If this is an actual application and not just, say, a home page, route your entire app through one main php file. Each 'page' in the app can be differentiated with an event id thats passed as a GET parameter, and dispatched via your classes (just as you'd do for messages/signals in a C program). Then, you have one single page that does all the includes, and you never, ever, have any ambiguity about about what has and has not been initialized.
GrandmasterB
by that logic I need to load all of the files that any one page in the website might or might not need, creating zero ambiguity and a massive unnecessary overhead.
YuriKolovsky
If you use one of the bytecode caching systems the additional overhead is minimal because the php code is already compiled and loaded into memory. It may be counter-intuitive at first, but structuring your code in this way makes your code simpler, easier to maintain, and easier to scale. And that in turn will improve performance far more than including unused files will hinder it.
GrandmasterB
like APC?so that removes all of the overhead from including a hundred classes and creating a hundred objects for a single page load?what are the performance percentages??
YuriKolovsky
I never said there isnt *any* overhead from including files. Just that the overhead from doing that is not significant *compared* to the performance that you usually gain from having simpler, more maintainable code. Also, when you get rid of ambiguity in code, you remove a lot of possible vectors for failure.
GrandmasterB
A: 

simply use the autoloader and singleton pattern: create a class where you put all your classes(for example /modules/ )with the same filename as the contained class,remember ONLY the declaration.

now include this code(on a "main file")on top of all your pages:

function __autoload($class_name) {
    if(!ctype_alnum(str_replace(array('-','_'), '',$class_name)))//filename check,security reasons
        die('Module name not valid! ');
    require_once 'modules/'.$class_name.'.php';//load the class
}

you may want to create a singleton class(it's a object pattern,it basically ensure that only 1 entity of the class exists)

file:UserClass.php

<?php
class UserClass{
    private static $istance=null;
    private function UserClass($db){
        //your constructor code here
    };
    private static function getIstance($db){//you can call it init($db) and create a getInstace() that only return the instance,i prefer that way,do as you want.
        if($istance==null)
            $istance=new UserClass($db);
        return $istance;
    };
    function login($credentials){
            //....
    }
    //...other functions...
}
?>

now to use it you can simply do like so:

require 'main.php';//require the autoloader
$user=UserClass::getIstance($db);//the class file will be automatically included and a new istance will be created
$user->login($credentials1);
$user->login($credentials2);
$user=UserClass::getIstance($db);//no new istance will be created,only returned
$user->login($credentials3);
$user2=UserClass::getIstance($db);//no new istance will be created,only returned
$user2->login($credentials4);

//Userclass($db);// don't use like that,it will give you ERROR(it's private like singleton pattern says)
Plokko