2013-05-25 2 views
1
<?php 
require_once BLOCKS_ROOT_ENGINE . "Zend/Loader/StandardAutoloader.php"; 
//require_once BLOCKS_ROOT_ENGINE."library/Zend/Config/Reader/Xml.php"; 

class Engine { 
    static public function start() { 
     $autoLoader = new Zend\Loader\StandardAutoloader(array(
      'fallback_autoloader' => true, 
     )); 
     // register our StandardAutoloader with the SPL autoloader 
     $autoLoader->register(); 


     $config = new Engine_Zend_Config_Reader_Xml(); 
     //echo $config->config->layout->default->head; 
     $root = new Core_Root_Blocks_Root(); 
    } 
} 

Выше расположен в Engine/Engine.phpФатальная ошибка: Интерфейс «Zend Config чтения ReaderInterface»

Библиотека Zend находится в Engine/Zend/* автозагрузчика успешно находит класс Xml. Но по какой-то странной причине он не может найти интерфейс, который он реализует. Что я делаю не так.

Структура каталогов

enter image description here

xml.php

<?php 
/** 
* Zend Framework (http://framework.zend.com/) 
* 
* @link  http://github.com/zendframework/zf2 for the canonical source repository 
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) 
* @license http://framework.zend.com/license/new-bsd New BSD License 
*/ 

namespace Zend\Config\Reader; 

use XMLReader; 
use Zend\Config\Exception; 

/** 
* XML config reader. 
*/ 
class Xml implements ReaderInterface 
{ 
    /** 
    * XML Reader instance. 
    * 
    * @var XMLReader 
    */ 
    protected $reader; 

    /** 
    * Directory of the file to process. 
    * 
    * @var string 
    */ 
    protected $directory; 

    /** 
    * Nodes to handle as plain text. 
    * 
    * @var array 
    */ 
    protected $textNodes = array(
     XMLReader::TEXT, 
     XMLReader::CDATA, 
     XMLReader::WHITESPACE, 
     XMLReader::SIGNIFICANT_WHITESPACE 
    ); 

    /** 
    * fromFile(): defined by Reader interface. 
    * 
    * @see ReaderInterface::fromFile() 
    * @param string $filename 
    * @return array 
    * @throws Exception\RuntimeException 
    */ 
    public function fromFile($filename) 
    { 
     if (!is_file($filename) || !is_readable($filename)) { 
      throw new Exception\RuntimeException(sprintf(
       "File '%s' doesn't exist or not readable", 
       $filename 
      )); 
     } 

     $this->reader = new XMLReader(); 
     $this->reader->open($filename, null, LIBXML_XINCLUDE); 

     $this->directory = dirname($filename); 

     set_error_handler(
      function ($error, $message = '', $file = '', $line = 0) use ($filename) { 
       throw new Exception\RuntimeException(sprintf(
        'Error reading XML file "%s": %s', 
        $filename, $message 
       ), $error); 
      }, E_WARNING 
     ); 
     $return = $this->process(); 
     restore_error_handler(); 

     return $return; 
    } 

    /** 
    * fromString(): defined by Reader interface. 
    * 
    * @see ReaderInterface::fromString() 
    * @param string $string 
    * @return array|bool 
    * @throws Exception\RuntimeException 
    */ 
    public function fromString($string) 
    { 
     if (empty($string)) { 
      return array(); 
     } 
     $this->reader = new XMLReader(); 

     $this->reader->xml($string, null, LIBXML_XINCLUDE); 

     $this->directory = null; 

     set_error_handler(
      function ($error, $message = '', $file = '', $line = 0) { 
       throw new Exception\RuntimeException(sprintf(
        'Error reading XML string: %s', 
        $message 
       ), $error); 
      }, E_WARNING 
     ); 
     $return = $this->process(); 
     restore_error_handler(); 

     return $return; 
    } 

    /** 
    * Process data from the created XMLReader. 
    * 
    * @return array 
    */ 
    protected function process() 
    { 
     return $this->processNextElement(); 
    } 

    /** 
    * Process the next inner element. 
    * 
    * @return mixed 
    */ 
    protected function processNextElement() 
    { 
     $children = array(); 
     $text  = ''; 

     while ($this->reader->read()) { 
      if ($this->reader->nodeType === XMLReader::ELEMENT) { 
       if ($this->reader->depth === 0) { 
        return $this->processNextElement(); 
       } 

       $attributes = $this->getAttributes(); 
       $name  = $this->reader->name; 

       if ($this->reader->isEmptyElement) { 
        $child = array(); 
       } else { 
        $child = $this->processNextElement(); 
       } 

       if ($attributes) { 
        if (!is_array($child)) { 
         $child = array(); 
        } 

        $child = array_merge($child, $attributes); 
       } 

       if (isset($children[$name])) { 
        if (!is_array($children[$name]) || !array_key_exists(0, $children[$name])) { 
         $children[$name] = array($children[$name]); 
        } 

        $children[$name][] = $child; 
       } else { 
        $children[$name] = $child; 
       } 
      } elseif ($this->reader->nodeType === XMLReader::END_ELEMENT) { 
       break; 
      } elseif (in_array($this->reader->nodeType, $this->textNodes)) { 
       $text .= $this->reader->value; 
      } 
     } 

     return $children ?: $text; 
    } 

    /** 
    * Get all attributes on the current node. 
    * 
    * @return array 
    */ 
    protected function getAttributes() 
    { 
     $attributes = array(); 

     if ($this->reader->hasAttributes) { 
      while ($this->reader->moveToNextAttribute()) { 
       $attributes[$this->reader->localName] = $this->reader->value; 
      } 

      $this->reader->moveToElement(); 
     } 

     return $attributes; 
    } 
} 

ERROR

enter image description here

+0

Так вы говорите класс 'Engine_Zend_Config_Reader_Xml' успешно, но автоматически загружаются интерфейсы, имеющиеся в ZF он реализует не? Можете ли вы предоставить немного больше информации о файловой структуре вашего приложения вместе с тем, какие папки у вас есть на пути включения? –

+0

@TimFountain Привет, спасибо за ответ, я не на компьютере, но я получу эту информацию вам как можно скорее. На данный момент я могу дать ответ «Да». Ошибка, которую я получаю, не может найти класс интерфейса, который реализует Reader_Xml. – numerical25

+0

. Я предоставил более подробную информацию, включая сообщение об ошибке и структуре каталогов. – numerical25

ответ

1

Я думаю, что вы пропустили, чтобы установить включают пути к Zend Framework библиотеки в ваш index.php файл.

Класс автозагрузчика загружается, потому что вы добавляете require_once в точный файл с определением класса автозагрузчика. Как я понимаю BLOCKS_ROOT_ENGINE константа определена в вашем index.php.

Также я предполагаю, что вы добавили как-то /opt/local/apache2/htdocs/blocks путь для включения путей в index.php - это потому, что автозагрузчик может загрузить класс Engine_Zend_Config_Reader_Xml.

Необходимо добавить BLOCKS_ROOT_ENGINE в ваш index.php, чтобы включить список маршрутов, позволяющий автозагрузчику найти Zend\Config\Reader\ReaderInterface.

+0

BLOCKS_ROOT_ENGINE находится внутри index.php – numerical25

+0

что еще включить пути, которые я должен установить, чтобы заставить эту работу работать – numerical25

+0

@ numerical25 Пожалуйста, добавьте содержимое вашего 'index.php'. к вашему сообщению – zavg

0

Не уверен, что это ваш случай, но как только я столкнулся с странными проблемами с моими учениками с разрешения. Один студент (с правами root) сделал что-то с разрешениями на папку, и нам не удалось выяснить, что - но файлы в этой папке больше не могут быть доступны php.

Даже file_exists() вернулся с ошибкой. Решите проблему, скопировав всю папку, удалив оригинал и переименовав скопированную папку с оригинальным именем.

Проверьте, соответствуют ли ваши разрешения.

0

Ну, проблема была связана с тем, что я установил автозагрузчик. Я скачал скелет ZF2 и нашел этот файл, который был весьма полезным для создания

<?php 
/** 
* Zend Framework (http://framework.zend.com/) 
* 
* @link  http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository 
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) 
* @license http://framework.zend.com/license/new-bsd New BSD License 
*/ 

/** 
* This autoloading setup is really more complicated than it needs to be for most 
* applications. The added complexity is simply to reduce the time it takes for 
* new developers to be productive with a fresh skeleton. It allows autoloading 
* to be correctly configured, regardless of the installation method and keeps 
* the use of composer completely optional. This setup should work fine for 
* most users, however, feel free to configure autoloading however you'd like. 
*/ 

// Composer autoloading 
if (file_exists('vendor/autoload.php')) { 
    $loader = include 'vendor/autoload.php'; 
} 

$zf2Path = false; 

if (is_dir('vendor/ZF2/library')) { 
    $zf2Path = 'vendor/ZF2/library'; 
} elseif (getenv('ZF2_PATH')) {  // Support for ZF2_PATH environment variable or git submodule 
    $zf2Path = getenv('ZF2_PATH'); 
} elseif (get_cfg_var('zf2_path')) { // Support for zf2_path directive value 
    $zf2Path = get_cfg_var('zf2_path'); 
} 

if ($zf2Path) { 
    if (isset($loader)) { 
     $loader->add('Zend', $zf2Path); 
    } else { 
     include $zf2Path . '/Zend/Loader/AutoloaderFactory.php'; 
     Zend\Loader\AutoloaderFactory::factory(array(
      'Zend\Loader\StandardAutoloader' => array(
       'autoregister_zf' => true 
      ) 
     )); 
    } 
} 

if (!class_exists('Zend\Loader\AutoloaderFactory')) { 
    throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.'); 
} 
Смежные вопросы