Black Friday = Pricewatch Bekijk onze selectie van de beste Black Friday-deals en voorkom een miskoop.

[php] classloader voor iedereen

Pagina: 1
Acties:
  • 531 views

  • 2playgames
  • Registratie: Februari 2005
  • Laatst online: 01-06 15:19
Zoals jullie wel weten heeft PHP5 autloading, waarbij klassen on-the-fly geladen worden als ze nodig zijn. Voor een persoonlijk project heb ik een classloader-klasse gemaakt die dit versimpelt. Je include de klasse, geeft aan waar de rest van je klassen zijn te vinden en klaar ben je.
Om de wereld een stukje beter te maken (kleeein stukje) wil ik hem graag met jullie delen. Oh ja, feedback is natuurlijk ook welkom :)

classloader.php:
PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php

/**
 * Include at the beginning of your app and call
 * ClassLoader::addPath($pathToClassesDirectory);
 */

/**
 * A static class containing<br/>
 * - a list of classes<br/>
 * - a function to add the contents of a directory to the list<br/>
 * - a function to include a specific classfile<br/>
 * Used with __autoload() or spl_autoload_register(), this provides
 * automatic class loading, without worries.
 * @author Bart van Heukelom
 */
class ClassLoader {
    
    private static $classList = array();

    /**
     * Add the contents of a directory to the class list. This directory should
     * contain only class files following the naming format "ClassName.php". It does
     * not matter if they are directly in the directory, or in a subdirectory.
     * You can also choose to use directories as "namespaces". For example,
     * if you call addPath('/path', '_'), the file '/path/Foo/Bar.php' must
     * contain the class 'Foo_Bar'. This mode is mainly for compatibility with some
     * libraries.
     * @param string $directory The path to a directory of classes to add.
     * @param string $separator The namespace separator to optionally use
     */
    public static function addPath($directory, $separator = null, $base = null) {
    
        if ($directory{strlen($directory) - 1} != DIRECTORY_SEPARATOR) {
            $directory .= DIRECTORY_SEPARATOR; // add trailing slash
        }
        
        if(!is_dir($directory)) { return; }
        
        $handle = opendir($directory);
        while ($file = readdir($handle)) {
            
            $fileLen = strlen($file);
            $completeFile = $directory . $file;
            
            if ($file{0} == '.') { continue; }
            
            if (is_dir($directory . $file)) {
                if (!is_null($separator)) {
                    if (is_null($base)) {
                        $newbase = $file;
                    } else {
                        $newbase = $base . $separator . $file;
                    }
                } else {
                    $newbase = null;
                }
                self::addPath($completeFile, $separator, $newbase);
            } else if (is_file($completeFile) && substr($file, $fileLen - 4) == '.php') {
                $className = substr($file, 0, $fileLen - 4);
                if (!is_null($separator)) {
                    $className = $base . $separator . $className;
                }
                if (isset(self::$classList[$className])) {
                    throw new Exception('Class file found twice: ' . $className);
                }
                self::$classList[$className] = realpath($completeFile);
            }
        }
        closedir($handle);
    }
    
    /**
     * Load a class, if it exists.
     * @param string $className The class to load.
     */
    public static function load($className) {
        if(isset(self::$classList[$className])) {
            require_once self::$classList[$className];
        }
    }
}

// neccesary, the class loader won't be used by PHP if this is not done
spl_autoload_register(array('ClassLoader', 'load'));

?>


Voorbeeld van gebruik
/my/class/dir/someotherdirwhichdoesnotmatter/Foo.php
PHP:
1
2
3
4
5
6
7
8
9
<?php

class Foo {
   public static function bar() {
      echo 'Hello world';
   }
}

?>


index.php
PHP:
1
2
3
4
5
6
7
8
9
<?php

require 'classloader.php';
ClassLoader::addPath('/my/class/dir');

// now the file /my/class/dir/someotherdirwhichdoesnotmatter/Foo.php will automatically be loaded
Foo::bar();

?>


Veel plezier ermee >:)

http://www.bartvanheukelom.nl/fastmvc/index.php/Classloader

  • Cartman!
  • Registratie: April 2000
  • Niet online
Niet om t een of ander... maar ken je Zend_Loader ? :)

Heeft heel handig de registerAutoload functie die gewoon zoekt naar files in je include_path.. :)

Overigens is het gebruik van autoloading niet altijd aan te raden, het kan je performance behoorlijk indeuken.

  • 2playgames
  • Registratie: Februari 2005
  • Laatst online: 01-06 15:19
Maar is die Zend_Loader ook te gebruiken buiten het Zend framework?
Heeft heel handig de registerAutoload functie die gewoon zoekt naar files in je include_path..
Daar houd ik niet zo van. De naam include_path geeft al aan, daar zitten allerlei includes in, niet alleen bestanden met klassen. Als er dan ook een script.php inzit, die iets aanroept wat je niet zomaar aan wil roepen (in de database of zo) en je vraagt per ongeluk om de klasse Script, gaat het fout. Maar eerlijk is eerlijk, dit verschilt per applicatie, en is misschien ook een kwestie van smaak.

Sowieso zoekt mijn classloader ook in subdirectories. Handig als je meer dan 10 klassen hebt ;)

[ Voor 8% gewijzigd door 2playgames op 07-10-2008 21:27 ]


  • Chip.
  • Registratie: Mei 2006
  • Niet online
Yup Zend_Loader is ook buiten het Zend Framework te gebruiken aangezien het Zend Framework eigenlijk helemaal geen framework is in feite maar gewoon een bij een stapeling van classes waarvan een aantal dan ook met elkander kunnen samenwerken.

Verwijderd

Wouser schreef op dinsdag 07 oktober 2008 @ 21:46:
Yup Zend_Loader is ook buiten het Zend Framework te gebruiken aangezien het Zend Framework eigenlijk helemaal geen framework is in feite maar gewoon een bij een stapeling van classes waarvan een aantal dan ook met elkander kunnen samenwerken.
Wat is volgens jou dan een framework?

  • Cartman!
  • Registratie: April 2000
  • Niet online
Wouser, dat is juist t mooie aan Zend Framework (whats in a name ;))... je zit niet vast aan installaties of structuren.. je gebruik wat je wilt gebruiken en de rest laat je lekker links liggen. Voor de niet-Zend Framework gebruikers is het handig dat alles los te gebruiken is juist ;)

  • Chip.
  • Registratie: Mei 2006
  • Niet online
Verwijderd schreef op dinsdag 07 oktober 2008 @ 22:07:
[...]

Wat is volgens jou dan een framework?
Precies wat Cartmen eigenlijk al zegd. Bij ieder ander framework zit je vast aan wat en hoe ze het aanbieden bij Zend niet.
en @ Cartmen zelf gebruik ik ook zend werkt gewoon perfect :)

  • Creepy
  • Registratie: Juni 2001
  • Laatst online: 02:24

Creepy

Tactical Espionage Splatterer

Zie ook [Alg] Welke tools heb jij gemaakt? - deel III. Daar kan je je code dan ook eventueel kwijt. Het is leuk en aardig dat je je code wilt delen hier maar als iedereen dat in een eigen topic zou doen krijgen we hier een wildgroei aan topics met "handige" code.

"I had a problem, I solved it with regular expressions. Now I have two problems". That's shows a lack of appreciation for regular expressions: "I know have _star_ problems" --Kevlin Henney


  • NMe
  • Registratie: Februari 2004
  • Laatst online: 09-09 13:58

NMe

Quia Ego Sic Dico.

'E's fighting in there!' he stuttered, grabbing the captain's arm.
'All by himself?' said the captain.
'No, with everyone!' shouted Nobby, hopping from one foot to the other.

Pagina: 1

Dit topic is gesloten.