Перейти из форума на сайт.

НовостиФайловые архивы
ПоискАктивные темыТоп лист
ПравилаКто в on-line?
Вход Забыли пароль? Первый раз на этом сайте? Регистрация
Компьютерный форум Ru.Board » Интернет » Web-программирование » PHP: Полезные (интересные и оригинальные) решения

Модерирует : Cheery

 Версия для печати • ПодписатьсяДобавить в закладки
На первую страницук этому сообщениюк последнему сообщению

Открыть новую тему     Написать ответ в эту тему

sTa1kEr



Member
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору

Код:
<?php
 
// Абсолютный путь к корню сайта
if (!defined("AL_ROOT"))
   
define("AL_ROOT", "/home/autoload/www");
 
// Путь к каталогу с классами относительно AL_ROOT
if (!defined("AL_CLASSDIR"))
   
define("AL_CLASSDIR", "/classes");
 
// Глубина сканирования директорий
if (!defined("AL_LEVEL"))
   
define("AL_LEVEL", 5);
 
// Режим отладки
if (!defined("AL_DEBUG"))
   
define("AL_DEBUG", true);
 
function
__autoload($className)
{
   
Autoload::Instance()->LoadClass($className);
}
 
function
Debug($msg)
{
   if (
AL_DEBUG)
   {
      if (
defined("STDOUT"))
      {
         
fwrite(STDOUT, $msg);
      }
      else
      {
         echo
nl2br($msg);
         
flush();
      }
   }
}
 
class
Autoload
{
   private static
$_thisInstance = null;
 
   private
$Pattern = null;
 
   private
$ClassMap = null;
 
   private
$IsParsed = false;
 
   private function
__construct()
   {
      if (!
file_exists("classes.map"))
      {
         
$this->ClassMap = array(array(), array());
         
$this->ParseSources();
         
$this->Serialize();
      }
      else
      {
         
$this->ClassMap = unserialize(file_get_contents("classes.map"));
      }
   }
 
   public function
ParseSources()
   {
     
Debug("Start parsing classes.\n");
     
ini_set("max_execution_time", 900);
     
set_time_limit(900);
     
ignore_user_abort();
 
      if (
$this->Pattern === null)
      {
         for (
$i = 0; $i < AL_LEVEL + 1; $i++)
         {
           
$level[$i] = implode("*", array_fill(0, $i + 1, "/"));
         }
         
$this->Pattern = "{".implode(",", $level)."}*.php";
      }
 
     
Debug("Get list php files.\n");
      foreach (
glob(AL_ROOT.AL_CLASSDIR.$this->Pattern, GLOB_BRACE) as $fileName)
      {
         
$this->ParseFile(substr($fileName, strlen(AL_ROOT)));
      }
 
     
Debug("Parse successfull finished.\n");
     
$this->IsParsed = true;
   }
 
   private function
Serialize()
   {
      if (
count($this->ClassMap[0]) > 0 && count($this->ClassMap[1]) > 0)
      {
         
file_put_contents("classes.map", serialize($this->ClassMap));
      }
   }
 
   private function
ParseFile($fileName)
   {
     
Debug("Parse file $fileName: ");
     
$lastModified = filemtime(AL_ROOT.$fileName);
      if (isset(
$this->ClassMap[1][$fileName]))
      {
         if (
$lastModified <= $this->ClassMap[1][$fileName])
         {
           
Debug("File not modified.\n");
            return;
         }
         else
         {
           
$this->UnsetFile($fileName);
         }
      }
     
$source = file_get_contents(AL_ROOT.$fileName);
     
$tokens = token_get_all($source);
      while ((
$token = array_shift($tokens)) !== null)
      {
         if (
is_array($token) && ($token[0] == T_CLASS || $token[0] == T_INTERFACE) && $tokens[1][0] == T_STRING)
         {
            if (isset(
$this->ClassMap[0][$tokens[1][1]]))
            {
               
Debug("\nWarning! Class {$tokens[1][1]} alrady declared in {$this->ClassMap[0][$tokens[1][1]]}\n");
            }
            else
            {
               
$this->ClassMap[0][$tokens[1][1]] = $fileName;
            }
           
Debug("{$tokens[1][1]}; ");
         }
      }
     
Debug("\n");
     
$this->ClassMap[1][$fileName] = $lastModified;
   }
 
   private function
UnsetFile($fileName)
   {
      unset(
$this->ClassMap[1][$fileName]);
      while((
$key = array_search($fileName, $this->ClassMap[0])) !== false)
      {
         unset(
$this->ClassMap[0][$key]);
      }
      if (
$this->IsParsed)
      {
         
$this->Serialize();
      }
   }
 
   private function
UnsetClass($className)
   {
     
$file = $this->ClassMap[0][$className];
     
$this->UnsetFile($file);
   }
 
   
/**
    * @return Autoload
    */
   
public static function Instance()
   {
      if (
Autoload::$_thisInstance === null)
      {
         
Autoload::$_thisInstance = new Autoload();
      }
      return
Autoload::$_thisInstance;
   }
 
   public function
LoadClass($className)
   {
      if (isset(
$this->ClassMap[0][$className]))
      {
         @include_once(
AL_ROOT.$this->ClassMap[0][$className]);
         if (!
class_exists($className, false) && !interface_exists($className, false))
         {
           
$this->UnsetClass($className);
           
$this->Serialize();
           
$this->LoadClass($className);
         }
      }
      else
      {
         if (!
$this->IsParsed)
         {
           
$this->ParseSources();
           
$this->Serialize();
           
$this->LoadClass($className);
         }
      }
   }
}
 
?>

Всего записей: 279 | Зарегистр. 28-07-2005 | Отправлено: 18:07 03-05-2007 | Исправлено: sTa1kEr, 18:10 03-05-2007
Открыть новую тему     Написать ответ в эту тему

На первую страницук этому сообщениюк последнему сообщению

Компьютерный форум Ru.Board » Интернет » Web-программирование » PHP: Полезные (интересные и оригинальные) решения


Реклама на форуме Ru.Board.

Powered by Ikonboard "v2.1.7b" © 2000 Ikonboard.com
Modified by Ru.B0ard
© Ru.B0ard 2000-2024

BitCoin: 1NGG1chHtUvrtEqjeerQCKDMUi6S6CG4iC

Рейтинг.ru