phpoopclassnomenclaturespl-autoload-register

Using spl_autoload_register to handle multiple classes inside a single file


With spl_autoload_register, it's possible to load classes automatically. Let's take a simple example using two files:

index.php

<?php
    spl_autoload_extensions (".php");
    spl_autoload_register ();

    $class = new \kitchen\oven;

    var_dump ($class);
    var_dump (new kitchen\Microwave);
    var_dump (new kitchen\Oven);
?>

kitchen/oven.php

<?php
    namespace kitchen {
        class Microwave {
            private $potency;

            public function get_potency () {return $this->potency;}
            public function set_potency ($potency) {$this->potency = $potency;}
        }

        class Oven {
            private $temperature;

            public function get_temperature () {return $this->temperature;}
            public function set_temperature ($temperature) {$this->temperature = $temperature;}
        }
    }
?>

Running $ php index.php gives the following output:

object(kitchen\Oven)#1 (1) {
  ["temperature":"kitchen\Oven":private]=>
  NULL
}
object(kitchen\Microwave)#2 (1) {
  ["potency":"kitchen\Microwave":private]=>
  NULL
}
object(kitchen\Oven)#2 (1) {
  ["temperature":"kitchen\Oven":private]=>
  NULL
}

Everything is ok, my only concern is about nomenclature. I *MUST* nominate my file with the same name of any class inside that file. Is there any way that allow me to use a more generic name ? I wish I could use "kitchen/objects.php" instead of "kitchen/oven.php".

Thanks.


Solution

  • The only way I can think around this would be to include all PHP files in a namespace's directory in your spl-autoload-register method. Your autoload method would only be run once, but it would potentially load a lot more than you had anticipated and/or needed.

    I believe it's good practice to only have 1 class per file and have the filename share the name of the class. Yes you have more files, but it simplifies refactoring and makes your file structure easier for other developers to work with.