2015-10-13 53 views
0

我在Zend的FW 2是新的,我嘗試顯示佈局從數據庫中的數據,但我收到錯誤:Zend公司在佈局2動態內容視圖助手

Catchable fatal error: Argument 1 passed to Application\View\Helper\HotNews::__construct() must be an instance of Zend\Db\Adapter\Adapter, none given, called in C:\xampp\htdocs\webtruonghoc\vendor\ZF2\library\Zend\ServiceManager\AbstractPluginManager.php on line 207 and defined in C:\xampp\htdocs\webtruonghoc\module\Application\src\Application\View\Helper\HotNews.php on li 

功能getViewHelperConfig在Module.php:

在module.config.php
public function getViewHelperConfig() 
{ 
    return array(
      'factories' => array(
        'hotNews' => function($sm) { 
         $adapter = $sm->getServiceLocator()->get('Application\Model\NewsTable'); 
         return new HotNews($adapter); 
        }, 
      ), 
    ); 
} 

添加代碼:

'view_helpers' => array(
      'invokables' => array(
        'hotnews' => 'Application\View\Helper\HotNews', 
      ), 

文件HotNews.php:

<?php 


namespace Application\View\Helper; 

use Zend\Authentication\AuthenticationService; 
use Zend\View\Helper\AbstractHelper; 
use Zend\Db\Adapter\Adapter; 

class HotNews extends AbstractHelper 
{ 
    protected $adapter; 

    public function __construct(Adapter $adapter) 
    { 
     $this->adapter = $adapter; 
    } 

    public function __invoke() 
    { 
     $sql="SELECT * FROM news order by date DESC limit 0,4"; 
     return $resultSet = $this->adapter->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE); 
    } 
} 

和最終我顯示佈局數據:

<?php $hotnews = $this->hotNews(); 
          var_dump($hotnews); 
        ?> 

難道我錯過了什麼?

回答

2

看起來你期待你的模型被設置爲服務。但可能沒有正確設置服務。在你module.config.php文件,應該是在「service_manager」 =>「工廠」的條目:

return array(  
    'service_manager' => array(
     'factories' => array(
      'Application\Model\NewsTable' => function (ServiceLocatorInterface $serviceLocator) { 
       //... returns an instance of Application\Model\NewsTable 
      } 
     ) 
    ) 
); 

你的SQL有一個錯誤在裏面。此外,您不應該在視圖幫助器中執行SQL語句,並將select *的整個結果集傳遞給視圖也是不好的。我會將SQL放入一個Repository類中,該類將返回表示您的數據模型的DTO對象。然後,您可以將資源庫注入ViewHelper中,並在視圖中使用這些DTO。

+0

我在Module.php使用函數getServiceConfig(): 返回陣列( \t \t \t '工廠'=>數組( \t \t \t \t \t '應用程序\模型\ NewsTable'=>功能($ SM){ \t \t \t \t \t \t $ tableGateway = $ SM->的get( 'NewsTableGateway'); \t \t \t \t \t \t $噸able = new NewsTable($ tableGateway); \t \t \t \t \t \t return $ table; \t \t \t \t \t}, 是嗎? –