Php class load library

spl_autoload

Эта функция представляет из себя базовую реализацию метода __autoload() . Если она не указана и spl_autoload_register() вызывается без каких-либо параметров, то при каждом последующем вызове __autoload() будет использоваться именно эта функция.

Список параметров

Имя класса (и пространства имён), которое требуется загрузить.

По умолчанию функция будет искать файлы с расширениями .inc и .php. по всем include-путям, где может располагаться искомый класс.

Возвращаемые значения

Функция не возвращает значения после выполнения.

Ошибки

Вызывает исключение LogicException , если класс не найден и отсутствуют другие зарегистрированные автозагрузчики.

Список изменений

Версия Описание
8.0.0 file_extensions теперь допускает значение null.

User Contributed Notes 9 notes

Note, that the default autoload implementation is written in C land and is always slightly faster then your native PHP one.

Here is a trick to use default implementation with any configuration:

// Your custom class dir
define ( ‘CLASS_DIR’ , ‘class/’ )

// Add your class dir to include path
set_include_path ( get_include_path (). PATH_SEPARATOR . CLASS_DIR );

// You can use this trick to make autoloader look for commonly used «My.class.php» type filenames
spl_autoload_extensions ( ‘.class.php’ );

// Use default autoload implementation
spl_autoload_register ();
?>

This also works with namespaces out of the box. So you can write code like «use My\Name\Object» and it will map to «class/My/Name/Object.class.php» file path!

Just thought I’d react to simast at gmail dot com’s note: While he has a point in saying C outperforms PHP, his suggestion is micro-optimization. I’m not 100% against micro-optimizing code, but if you do, go all the way:

// Your custom class dir
define ( ‘CLASS_DIR’ , ‘class/’ )

// Add your class dir to include path
set_include_path ( get_include_path (). PATH_SEPARATOR . CLASS_DIR );

This adds the include path to THE END of the paths PHP will scan for the class file , resulting in a bunch of misses ( file — not — found ‘s) before actually looking into the CLASS_DIR.
A more sensible approach, then would be to write

set_include_path(
CLASS_DIR.
PATH_SEPARATOR,
get_include_path()
);

Note this function will LOWERCASE the class names its looking for, dont be confused when it cant find Foo_Bar.php

also, unlike most other autoloader code snippets, this function DOES NOT translate underscores to slashes.

class Foo_Bar <>
will load foo_bar.php and will not try to load foo/bar.php

Note that, the orders of file extensions is important for performance. You should make the priority of your favourite file extension higest or use only one extension for your class files. Check out this example:

ClassA.php
?>
ClassB.php
?>
ClassC.php
?>
ClassD.php
?>
ClassE.php
?>

1. Simple:
// default priority: .inc .php
for( $n = 65 ; $n < 70 ; $n ++) $className = 'Class' . chr ( $n );
spl_autoload ( $className );
$ins = new $className ;
echo $ins -> val . ‘
‘ ;
>
// 4.2 miliseconds
?>

2. Change priority:
spl_autoload_extensions ( ‘.php,.inc’ );
// new priority: .php .inc
for( $n = 65 ; $n < 70 ; $n ++) $className = 'Class' . chr ( $n );
spl_autoload ( $className );
$ins = new $className ;
echo $ins -> val . ‘
‘ ;
>
// 1.4 miliseconds
?>

Or you can use this simple function that runs a bit faster for the extensions with lower priority 🙂
function my_autoload ( $className , $extList = ‘.inc,.php’ ) $ext = explode ( ‘,’ , $extList );
foreach( $ext as $x ) $fname = $className . $x ;
if(@ file_exists ( $fname )) require_once( $fname );
return true ;
>
>
return false ;
>

for( $n = 65 ; $n < 70 ; $n ++) $className = 'Class' . chr ( $n );
my_autoload ( $className );
$ins = new $className ;
echo $ins -> val . ‘
‘ ;
>
// 2.6 miliseconds
?>

Safak Ozpinar — Istanbul University, Computer Engineering

The documentation is a little unclear when it says: «The lowercased name of the class (and namespace) being instantiated».

What it actually means is that the argument can be in whatever case you want, but it will be converted to lowercase before PHP starts looking for files. This is probably because in PHP, class names are case-insensitive (as well as function names and namespaces) so it needs to convert to some canonical format.

If you want to make the best use out of autoload with an APC cache don’t use spl_autoload. It uses relative paths and thus will perform a stat even with apc.stat=0 (either that, or it doesn’t work at all).

Instead make a custom function and use require/include with an absolute path (register it with spl_autoload_register).

Do NOT use *_once functions or a relative path. This will fail harder than spl_autoload.

Also avoid using file_exists and is_file. This will also perform a stat.

Why are stats bad? Because they access the file system. PHP does have a stat cache that helps, but it defeats the purpose of apc.stat = 0.

It’s also good to keep in mind that it’s good to keep your custom autoload function simple. This is my Loader class:

class Loader
<
public static function registerAutoload ()
return spl_autoload_register (array( __CLASS__ , ‘includeClass’ ));
>

public static function unregisterAutoload ()
return spl_autoload_unregister (array( __CLASS__ , ‘includeClass’ ));
>

public static function includeClass ( $class )
require( PATH . ‘/’ . strtr ( $class , ‘_\\’ , ‘//’ ) . ‘.php’ );
>
>

?>

Also want to point out that APC does an optimization with require/include (not *_once) with relative paths if require/include is done in the global scope (and isn’t conditional). So it would be a good idea to explicitly include files you know you’re going to use on every request (but don’t use *_once). You could, for example, add a «registerProfiledAutoload» to the above class and keep track of what you’re including to help you determine what you could explicitly include (during development, not production). The key is try not to make heavy use out of autoload.

If you must use relative paths and don’t care about having to lower-case your file-names then spl_autoload works great.

One small example that shows how you can use spl_autoload function in your MVC, Framewrk’s applications. For example, will use the Loader class.

/**
* Controller Directory Path
*
* @var Array
* @access protected
*/
protected $_controllerDirectoryPath = array();

/**
* Model Directory Path
*
* @var Array
* @access protected
*/
protected $_modelDirectoryPath = array();

/**
* Library Directory Path
*
* @var Array
* @access protected
*/
protected $_libraryDirectoryPath = array();

/**
* Constructor
* Constant contain my full path to Model, View, Controllers and Lobrary-
* Direcories.
*
* @Constant MPATH,VPATH,CPATH,LPATH
*/

public function __construct ()
$this -> modelDirectoryPath = MPATH ;
$this -> viewDirectoryPath = VPATH ;
$this -> controllerDirectoryPath = CPATH ;
$this -> libraryDirectoryPath = LPATH ;

spl_autoload_register (array( $this , ‘load_controller’ ));
spl_autoload_register (array( $this , ‘load_model’ ));
spl_autoload_register (array( $this , ‘load_library’ ));

log_message ( ‘debug’ , «Loader Class Initialized» );
>

/**
*——————————————————
* Load Library
*——————————————————
* Method for load library.
* This method return class object.
*
* @library String
* @param String
* @access public
*/
public function load_library ( $library , $param = null )
if ( is_string ( $library )) return $this -> initialize_class ( $library );
>
if ( is_array ( $library )) foreach ( $library as $key ) return $this -> initialize_class ( $library );
>
>
>

/**
*——————————————————
* Initialize Class
*——————————————————
* Method for initialise class
* This method return new object.
* This method can initialize more class using (array)
*
* @library String|Array
* @param String
* @access public
*/
public function initialize_class ( $library )
try if ( is_array ( $library )) foreach( $library as $class ) $arrayObject = new $class ;
>
return $this ;
>
if ( is_string ( $library )) $stringObject = new $library ;
>else throw new ISException ( ‘Class name must be string.’ );
>
if ( null == $library ) throw new ISException ( ‘You must enter the name of the class.’ );
>
> catch( Exception $exception ) echo $exception ;
>
>

/**
* Autoload Controller class
*
* @param string $class
* @return object
*/

public function load_controller ( $controller )
if ( $controller ) set_include_path ( $this -> controllerDirectoryPath );
spl_autoload_extensions ( ‘.php’ );
spl_autoload ( $class );
>
>

/**
* Autoload Model class
*
* @param string $class
* @return object
*/

public function load_models ( $model )
if ( $model ) set_include_path ( $this -> modelDirectoryPath );
spl_autoload_extensions ( ‘.php’ );
spl_autoload ( $class );
>
>

/**
* Autoload Library class
*
* @param string $class
* @return object
*/

public function load_library ( $library )
if ( $library ) set_include_path ( $this -> libraryDirectoryPath );
spl_autoload_extensions ( ‘.php’ );
spl_autoload ( $class );
>
>

Источник

Php class load library

Offline

    SirGecco
    Newbie

  • *
  • (10-31-2016, 02:40 PM) SirGecco Wrote: The question: Is it possible to load and utilize a Library in a Core Class?

    You could use require_once(‘path/to/Custom_library.php’)
    Thanks for your input. Unfortunately this approach provokes further error messages:
    Message:

    A PHP Error was encountered

    Message : Undefined property : Stellen_controller :: $bestjob_library

    Filename : controllers / Stellen_controller . php

    File : / home / gp / public_html / application / controllers / Stellen_controller . php
    Line : 32
    Function: _error_handler

    File : / home / gp / public_html / application / controllers / Stellen_controller . php
    Line : 19
    Function: controller

    File : / home / gp / public_html / index . php
    Line : 327
    Function: require_once

    Offline

      InsiteFX
      Super Moderator

  • ******
  • Offline

      SirGecco
      Newbie

  • *
  • Already causes an error message:

    Fatal error : Uncaught Error : Class ‘CI_Controller’ not found in / home / gp / public_html / system / core / CodeIgniter . php : 366 Stack trace : #0 /home/gp/public_html/application/core/MY_Log.php(14): get_instance() #1 /home/gp/public_html/system/core/Common.php(478): MY_Log->write_log(‘error’, ‘Severity: error. ‘) #2 /home/gp/public_html/system/core/Exceptions.php(105): log_message(‘error’, ‘Severity: error. ‘) #3 /home/gp/public_html/system/core/Common.php(662): CI_Exceptions->log_exception(‘error’, ‘Exception: Clas. ‘, ‘/home/gp/public. ‘, 366) #4 [internal function]: _exception_handler(Object(Error)) #5

    thrown in /home/gp/public_html/system/core/CodeIgniter.php on line 366
    Fatal error : Uncaught Error : Class ‘CI_Controller’ not found in / home / gp / public_html / system / core / CodeIgniter . php : 366 Stack trace : #0 /home/gp/public_html/application/core/MY_Log.php(14): get_instance() #1 /home/gp/public_html/system/core/Common.php(478): MY_Log->write_log(‘error’, ‘Severity: Error. ‘) #2 /home/gp/public_html/system/core/Exceptions.php(105): log_message(‘error’, ‘Severity: Error. ‘) #3 /home/gp/public_html/system/core/Common.php(627): CI_Exceptions->log_exception(‘Error’, ‘Uncaught Error. ‘, ‘/home/gp/public. ‘, 366) #4 /home/gp/public_html/system/core/Common.php(698): _error_handler(1, ‘Uncaught Error. ‘, ‘/home/gp/public. ‘, 366) #5 [internal function]: _shutdown_handler() #6
    thrown in /home/gp/public_html/system/core/CodeIgniter.php on line 366

    Offline

      InsiteFX
      Super Moderator

  • ******
  • 11-01-2016, 07:32 AM
    (This post was last modified: 11-01-2016, 07:33 AM by InsiteFX. Edit Reason: spelling error )

    Источник

    How to create a custom library in CodeIgniter

    Private: How To Create A Custom Library In CodeIgniter

    When we develop a website in CodeIgniter, we need some customized code. Though CodeIgniter has a big collection of useful libraries. But sometimes we need to define some custom codes. Code reusability is very important whether it is a small scale website or a large one. To accomplish this purpose, we can create our own libraries additionally. This article is all about how to create a custom library in CodeIgniter

    To create a custom library, we simply need to create a PHP class. Follow the steps mentioned below to create a custom library in CodeIgniter.
    The name of the library will be myLibrary.
    Steps to create a custom library in CodeIgniter.

    #1 Open Library folder

    Assuming that you are aware of the directory structure of CodeIgniter. To create your own library, open application/libraries folder. All the libraries defined by you will be residing in this library itself.

    #2 Create a library file

    In application/libraries folder, create a PHP file with name myLibrary.php. Now, to successfully create a library, you need to create a library class too.

    #3 Create Library Class

    Open the myLibrary.php file and create a class with the same name as file,i.e. myLibrary class. The code will be like I am mentioning below.

    Doing this will create the library. However, it is useless until you put some code in it.

    Источник

    Читайте также:  Replacing char in string python
  • Оцените статью