2012-06-18 2 views
0

Я изучаю oop и пытаюсь реализовать стандарты php PSR-0 & PSR-1 по пути. Я начал с создания небольшой структуры MVC на основе Swiftlet.Вызов функции-члена для не-объекта из другого класса

Я пытаюсь вызвать функции из моего базового контроллера Просмотр в контроллере, который я вызываю из URL-адреса, и я получаю «Вызов функции-члена-члена() для не-объекта в '.

Все классы загружаются нормально. Поэтому в моем контроллере я вызываю $ this-> view-> set ('helloWorld', 'Hello world!'); но я получаю сообщение об ошибке. У меня были некоторые проблемы с попыткой получить структуру пространства имен правильно, так что, возможно, это причина?

Вот структура файла:

index.php

Библиотека/bootstrap.php

Библиотека/view.php

Библиотека/controller.php

приложение/контроллеры/index.php

и вот код для каждого:

index.php

<?php 

namespace MVC; 

    // Bootstrap the application 
    require 'lib/Bootstrap.php'; 

    $app = new lib\Bootstrap; 

    spl_autoload_register(array($app, 'autoload')); 

    $app->run(); 
    $app->serve(); 

bootstrap.php

namespace MVC\lib; 

class Bootstrap 
{ 
    protected 
     $action  = 'index', 
     $controller, 
     $hooks  = array(), 
     $view 
     ; 

    /** 
    * Run the application 
    */ 

    function run() 
    { 
       ... Code that gets controller and the action form the url 

     $this->view = new \lib\View($this, strtolower($controllerName)); 

     // Instantiate the controller 
     $controllerName = 'app\Controllers\\' . basename($controllerName); 

     $this->controller = new $controllerName();      

     // Call the controller action 
     $this->registerHook('actionBefore'); 

     if (method_exists($this->controller, $this->action)) { 
      $method = new \ReflectionMethod($this->controller, $this->action); 

      if ($method->isPublic() && !$method->isFinal() && !$method->isConstructor()) { 
       $this->controller->{$this->action}(); 
      } else { 
       $this->controller->notImplemented(); 
      } 
     } else { 
      $this->controller->notImplemented(); 
     } 

     return array($this->view, $this->controller); 

    } 


<?php 

namespace MVC\lib; 

class Bootstrap 
{ 
    protected 
     $action  = 'index', 
     $args  = array(), 
     $config  = array(), 
     $controller, 
     $hooks  = array(), 
     $plugins = array(), 
     $rootPath = '/', 
     $singletons = array(), 
     $view 
     ; 

    /** 
    * Run the application 
    */ 

    function run() 
    { 
     // Determine the client-side path to root 
     if (!empty($_SERVER['REQUEST_URI'])) { 
      $this->rootPath = preg_replace('/(index\.php)?(\?.*)?$/', '', $_SERVER['REQUEST_URI']); 

      if (!empty($_GET['route'])) { 
       $this->rootPath = preg_replace('/' . preg_quote($_GET['route'], '/') . '$/', '', $this->rootPath); 
      } 
     } 

     // Extract controller name, view name, action name and arguments from URL 
     $controllerName = 'Index'; 

     if (!empty($_GET['route'])) { 
      $this->args = explode('/', $_GET['route']); 

      if ($this->args) { 
       $controllerName = str_replace(' ', '/', ucwords(str_replace('_', ' ', str_replace('-', '', array_shift($this->args))))); 
      } 

      if ($action = $this->args ? array_shift($this->args) : '') { 
       $this->action = str_replace('-', '', $action); 
      } 
     } 

     if (!is_file('app/Controllers/'. $controllerName . '.php')) { 
      $controllerName = 'Error404'; 
     } 

     $this->view = new \lib\View($this, strtolower($controllerName)); 

     // Instantiate the controller 
     $controllerName = 'app\Controllers\\' . basename($controllerName); 

     $this->controller = new $controllerName();      

     // Call the controller action 
     $this->registerHook('actionBefore'); 

     if (method_exists($this->controller, $this->action)) { 
      $method = new \ReflectionMethod($this->controller, $this->action); 

      if ($method->isPublic() && !$method->isFinal() && !$method->isConstructor()) { 
       $this->controller->{$this->action}(); 
      } else { 
       $this->controller->notImplemented(); 
      } 
     } else { 
      $this->controller->notImplemented(); 
     } 

     $this->registerHook('actionAfter'); 

     return array($this->view, $this->controller); 

    } 

<?php 

namespace MVC\lib; 

class Bootstrap 
{ 
    protected 
     $action  = 'index', 
     $args  = array(), 
     $config  = array(), 
     $controller, 
     $hooks  = array(), 
     $plugins = array(), 
     $rootPath = '/', 
     $singletons = array(), 
     $view 
     ; 

    /** 
    * Run the application 
    */ 

    function run() 
    { 
     // Determine the client-side path to root 
     if (!empty($_SERVER['REQUEST_URI'])) { 
      $this->rootPath = preg_replace('/(index\.php)?(\?.*)?$/', '', $_SERVER['REQUEST_URI']); 

      if (!empty($_GET['route'])) { 
       $this->rootPath = preg_replace('/' . preg_quote($_GET['route'], '/') . '$/', '', $this->rootPath); 
      } 
     } 

     // Extract controller name, view name, action name and arguments from URL 
     $controllerName = 'Index'; 

     if (!empty($_GET['route'])) { 
      $this->args = explode('/', $_GET['route']); 

      if ($this->args) { 
       $controllerName = str_replace(' ', '/', ucwords(str_replace('_', ' ', str_replace('-', '', array_shift($this->args))))); 
      } 

      if ($action = $this->args ? array_shift($this->args) : '') { 
       $this->action = str_replace('-', '', $action); 
      } 
     } 

     if (!is_file('app/Controllers/'. $controllerName . '.php')) { 
      $controllerName = 'Error404'; 
     } 

     $this->view = new \lib\View($this, strtolower($controllerName)); 

     // Instantiate the controller 
     $controllerName = 'app\Controllers\\' . basename($controllerName); 

     $this->controller = new $controllerName();      

     // Call the controller action 
     $this->registerHook('actionBefore'); 

     if (method_exists($this->controller, $this->action)) { 
      $method = new \ReflectionMethod($this->controller, $this->action); 

      if ($method->isPublic() && !$method->isFinal() && !$method->isConstructor()) { 
       $this->controller->{$this->action}(); 
      } else { 
       $this->controller->notImplemented(); 
      } 
     } else { 
      $this->controller->notImplemented(); 
     } 

     $this->registerHook('actionAfter'); 

     return array($this->view, $this->controller); 

    } 

Библиотека/view.php

namespace lib; 

class View 
{ 
    protected 
     $app, 
     $variables = array() 
     ; 

    public 
     $name 
     ; 

    /** 
    * Constructor 
    * @param object $app 
    * @param string $name 
    */ 
    public function __construct($app, $name) 
    { 
     $this->app = $app; 
     $this->name = $name; 
    } 


    /** 
    * Set a view variable 
    * @param string $variable 
    * @param mixed $value 
    */ 
    public function set($variable, $value = null) 
    { 
     $this->variables[$variable] = $value; 
    } 

и, наконец, приложение/контроллеры/index.php

namespace app\Controllers; 

class index extends \lib\Controller 

{ 

    public function test() 

    { 
      // This gets the error 
        $this->view->set('helloWorld', 'Hello world!'); 
    } 

} 
+0

Ermm. Вы никогда не устанавливаете $ this-> view в контроллере, поэтому он имеет значение null ... Я думаю, что вы упустили что-то в своем бутстрапе (вы отправили 3 из них кстати). Вы устанавливаете $ this-> view в Bootstrap, но никогда не передаете его контроллеру. – akimsko

ответ

0

Если это все код вашего контроллера, то $this->view не является объектом.
Попробуйте запустить следующий код:

namespace app\Controllers; 

class index extends \lib\Controller 
{ 
    public function test() 
    { 
      var_dump($this->view); 
      exit; 
      $this->view->set('helloWorld', 'Hello world!'); 
    } 

} 

Вы также должны знать, что в PHP, то __construct() методы не наследуются.
Я, должно быть, пострадал от черепно-мозговой травмы.

Ох .. и я не вижу, почему этот вопрос имеет бирка. Пока вы пытаетесь написать MVC-подобную вещь, сама проблема не имеет отношения к MVC как к архитектурному шаблону.

+0

yes Я получаю NULL, когда я пытаюсь var_dump –

Смежные вопросы