PHP spl_autoload_register

Today I used spl_autoload_register again.

This time to load default concrete classes. For example in my framework I have a class called SlibUser:

class SlibUser extends SlibRecord {
  public static function Load( $id ) {
    $args = array( 'id' => $id );    
    $data = db()->get_row( 'select * from /*prefix*/user where id = :id', $args );
    if ( $data ) { return new User( $data ); }
    return null;
  }
}

As you can see SlibUser creates a new User. That User can be provisioned by a user of my framework, but if they don’t specify a particular User definition I give them a default implementation with spl_autoload_register, e.g.:

<?php

function load_slib_mock( $class = false ) {

  //var_dump( $class );
  
  static $classes;
  static $files;
  
  if ( ! $files ) { $files = array(); }
  
  if ( ! $classes ) {
    
    $classes = array(
        
      // URL
      'Uri',
      'UriPath',
      'UriPathBuilder',
      'UriQuery',
      'UriQueryBuilder',
      'UriQueryNode',
        
      // framework:
      'Auth',
      'Column',
      'FrontController',
      'Option',
      'OptionGroup',
      'ResourceManager',
      'Schema',
      'Settings',
      'Table',
      'Variable',
      
      // database:
      'Database',
      'DatabaseUpgrader',
        
      // ORM:
      'Browser',
      'GeoipLocation',
      'HttpAccept',
      'HttpAcceptEncoding',
      'HttpAcceptLanguage',
      'HttpMethod',
      'HttpUserAgent',
      'Partition',
      'Request',
      'Role',
      'Session',
      'SessionSettings',
      'User',
      'UserPartition',
      'UserSettings'
    );
    
  }

  if ( ! in_array( $class, $classes ) ) { return false; }

  $path = "/var/tmp/slib-$class.php";

  if ( ! file_exists( $path ) ) {
  
    $content = "<?php class $class extends Slib$class {}";

    $file = fopen( $path, 'w' );

    if ( ! $file ) { throw new IOException( "Cannot write '$file'." ); }

    fwrite( $file, $content );

    fclose( $file );
    
  }
  
  require_once( $path );
  
  return true;
  
}

// autoload handler:
spl_autoload_register( 'load_slib_mock', true, true );

Leave a Reply