草庐IT

php - Zend 框架 2 : Database connection in view helper

coder 2024-04-27 原文

我发现了一些与此问题相关的其他帖子,但是我无法实现我想要的,所以我决定删除所有内容并在一些帮助下重新开始...

到目前为止,这是我的工作,它完成了工作,但数据是在数组中硬编码提供的,我需要创建一个数据库连接来获取这些数据。

在我的模块类中我有:

public function getViewHelperConfig()
{
    return array(
        'factories' => array(
            'liveStreaming' => function() {
                return new LiveStreaming();
            },
        ),
    );
}    

这是我在 View 助手中的代码:

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;

class LiveStreaming extends AbstractHelper
{ 

    protected $liveStreamingTable;

    public function __invoke()
    {
        $events = array(
            '1' => array('name' => 'Event name', 
                    'sport' => 'Soccer', 
                    'time' => '11:30'), 
            '2' => array('name' => 'Event name', 
                    'sport' => 'Soccer', 
                    'time' => '17:00'),             
        );
        return $events;
        //this is what should be used (or something like that) to get the data from the db...
        //return array('events' => $this->getLiveStreamingTable()->fetchAll() ); 
    }

    public function getLiveStreamingTable()
    {
    if (!$this->liveStreamingTable) {
           $sm = $this->getServiceLocator();
           $this->liveStreamingTable = $sm->get('LiveStreaming\Model\LiveStreamingTable');
       }
       return $this->liveStreamingTable;
    }   
}

所以,我想从数据库中获取$events 数组。我已经创建了 Application\Model\LiveStreamingApplication\Model\LiveStreamingTable(按照 ZF2 官方教程的说明),我需要一些帮助才能进行下一步,这可能与服务定位器有关。

最佳答案

你似乎快到了。唯一缺少的是从 View 助手中调用 $this->getServiceLocator(); 的能力(因为 AbstractHelper 不提供此方法)。

有两种选择

  • LiveStreamingTable 直接注入(inject) View 助手
  • 注入(inject) ServiceManager 本身并在助手中创建 LiveStreamingTable

选项 1 使 LiveStreamingTable 成为 View 助手的依赖项(在构造函数中键入提示)

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;
use LiveStreaming\Model\LiveStreamingTable;


class LiveStreaming extends AbstractHelper
{ 
  protected $liveStreamingTable;

  public function __construct(LiveStreamingTable $liveStreamingTable)
  {
    $this->liveStreamingTable = $liveStreamingTable;
  }

  public function getLiveStreamingTable()
  {
    return $this->liveStreamingTable;
  } 

}

然后工厂变成:

public function getViewHelperConfig()
{
    return array(
        'factories' => array(
            'liveStreaming' => function($sl) {
                // Get the shared service manager instance
                $sm = $sl->getServiceLocator(); 
                $liveStreamingTable = $sm->get('LiveStreaming\Model\LiveStreamingTable');
                // Now inject it into the view helper constructor
                return new LiveStreaming($liveStreamingTable);
            },
        ),
    );
}   

选项 2 - 实现 ServiceLocatorAwareInterface(使其再次成为 View 助手的依赖项)

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class LiveStreaming extends AbstractHelper implements ServiceLocatorAwareInterface
{ 
  protected $serviceLocator;

  protected $liveStreamingTable;

  public function __construct(ServiceLocatorInterface $serviceLocator)
  {
    $this->serviceLocator = $serviceLocator;
  }

  public function setServiceLocator(ServiceLocatorInterface $serviceLocator);

  public function getServiceLocator();

  public function getLiveStreamingTable()
  {
    if (null == $this->liveStreamingTable) {
      $this->liveStreamingTable = $this->getServiceLocator()->get('LiveStreaming\Model\LiveStreamingTable');
    }
    return $this->liveStreamingTable;
  } 

}

您的工厂将如下所示:

public function getViewHelperConfig()
{
    return array(
        'factories' => array(
            'liveStreaming' => function($sl) {
                // Get the shared service manager instance
                $sm = $sl->getServiceLocator(); 
                // Now inject it into the view helper constructor
                return new LiveStreaming($sm);
            },
        ),
    );
}  

就个人而言,我觉得从依赖注入(inject) (DI) 的角度来看,选项 1 更有意义 - 很明显,LiveStreamingTable 是创建查看助手。

编辑

确保你有 LiveStreaming\Model\LiveStreamingTable 服务也注册了服务管理器(正如我们在上面的代码中请求的那样 $sm->get('LiveStreaming\模型\LiveStreamingTable');)

// Module.php
public function getServiceConfig()
{
 return array(
   'factories' => array(

     'LiveStreaming\Model\LiveStreamingTable' => function($sm) {

       // If you have any dependencies for the this instance
       // Such as the database adapter etc either create them here 
       // or request it from the service manager
       // for example:
       $foo = $sm->get('Some/Other/Registered/Service');
       $bar = new /Directly/Created/Instance/Bar();

       return new \LiveStreaming\Model\LiveStreamingTable($foo, $bar);
     },

   ),
 );
}

关于php - Zend 框架 2 : Database connection in view helper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19787941/

有关php - Zend 框架 2 : Database connection in view helper的更多相关文章

  1. TimeSformer:抛弃CNN的Transformer视频理解框架 - 2

    Transformers开始在视频识别领域的“猪突猛进”,各种改进和魔改层出不穷。由此作者将开启VideoTransformer系列的讲解,本篇主要介绍了FBAI团队的TimeSformer,这也是第一篇使用纯Transformer结构在视频识别上的文章。如果觉得有用,就请点赞、收藏、关注!paper:https://arxiv.org/abs/2102.05095code(offical):https://github.com/facebookresearch/TimeSformeraccept:ICML2021author:FacebookAI一、前言Transformers(VIT)在图

  2. ruby - sinatra 框架的 MVC 模式 - 2

    我想开始使用“Sinatra”框架进行编码,但我找不到该框架的“MVC”模式。是“MVC-Sinatra”模式或框架吗? 最佳答案 您可能想查看Padrino这是一个围绕Sinatra构建的框架,可为您的项目提供更“类似Rails”的感觉,但没有那么多隐藏的魔法。这是使用Sinatra可以做什么的一个很好的例子。虽然如果您需要开始使用这很好,但我个人建议您将它用作学习工具,以对您来说最有意义的方式使用Sinatra构建您自己的应用程序。写一些测试/期望,写一些代码,通过测试-重复:)至于ORM,你还应该结帐Sequel其中(imho

  3. ruby-on-rails - 这个 C 和 PHP 程序员如何学习 Ruby 和 Rails? - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭9年前。我来自C、php和bash背景,很容易学习,因为它们都有相同的C结构,我可以将其与我已经知道的联系起来。然后2年前我学了Python并且学得很好,Python对我来说比Ruby更容易学。然后从去年开始,我一直在尝试学习Ruby,然后是Rails,我承认,直到现在我还是学不会,讽刺的是那些打着简单易学的烙印,但是对于我这样一个老练的程序员来说,我只是无法将它

  4. ruby-on-rails - 正确了解 Rails 框架的最佳方式是什么? - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭10年前。我一直在Rails上做两个项目,它们运行良好,但在这个过程中重新发明了轮子,自来水(和热水)和止痛药,正如我随后了解到的那样,这些已经存在于框架中。那么基本上,正确了解框架中所有智能部分的最佳方法是什么,这将节省时间而不是自己构建已经实现的功能?从第1页开始阅读文档?是否有公开所有内容的特定示例应用程序?一个特定的开源项目?所有的rails交通?还是完全

  5. ruby - 自动将院子文档框架添加到现有的 Rails 遗留代码中 - 2

    关闭。这个问题不符合StackOverflowguidelines.它目前不接受答案。我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。关闭4年前。Improvethisquestion我希望能够将模板化的YARD文档样式注释插入到我现有的Rails遗留应用程序中。目前它的评论很少。我想要具有指定参数的类header和方法header(通过从我假定的方法签名中提取)和返回值的占位符。在PHP代码中,我有一些工具可以检查代码并在适当的位置创建插入到代码中的文档header注释。在带有Ducktyping等的Ruby中,我确信诸如@params等类型之类

  6. ruby-on-rails - 具有六边形架构和 DCI 模式的框架和数据库适配器 - 2

    我尝试用Ruby设计一个基于Web的应用程序。我开发了一个简单的核心应用程序,在没有框架和数据库的情况下在六边形架构中实现DCI范例。核心六边形中有小六边形和网络,数据库,日志等适配器。每个六边形都在没有数据库和框架的情况下自行运行。在这种方法中,我如何提供与数据库模型和实体类的关系作为独立于数据库的关系。我想在将来将框架从Rails更改为Sinatra或数据库。事实上,我如何在这个核心Hexagon中实现完全隔离的rails和mongodb的数据库适配器或框架适配器。有什么想法吗? 最佳答案 ROM呢?(Ruby对象映射器)。还有

  7. python - Ruby 是否有相当于 Python 的扭曲框架作为网络抽象层? - 2

    据我了解,Python的扭曲框架为网络通信提供了更高级别的抽象(?)。我正在寻找在Rails应用程序中使用与twisted等效的Ruby。 最佳答案 看看EventMachine.它不像Twisted那样广泛,但它是围绕事件驱动网络编程的相同概念构建的。 关于python-Ruby是否有相当于Python的扭曲框架作为网络抽象层?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/9

  8. ruby-on-rails - 使用 Rails 以外的 Ruby 框架是否有任何潜在的缺点? - 2

    我想使用比Rails(Sinatra/Ramaze/Camping)更轻的框架,但我担心这样做我将无法使用许多以插件形式为Rails定制的共享库.这是一个主要问题,还是这些插件中的大多数都可以跨不同的Ruby框架使用?使用Ruby框架而不是Rails是否还有其他潜在的缺点? 最佳答案 您仍然可以使用gems在你提到的所有框架中,很多东西都是可重用的。想要交换一个新的ORM,没问题。想要一个花哨的shmacy语法高亮,没问题。Rails一直在大力插入摆脱旧的插件模型,转而使用gems。如果其他框架之一符合您的需求,最好使用它。请记住,

  9. ruby - 应该 validate_format_of 。 not_with 在框架中有问题(或者在我的理解中) - 2

    我将以下代码放入RSpec测试中:it{shouldvalidate_format_of(:email).not_with('test@test')}并设置实际的类:validates:email,:presence=>true,:format=>/\b[A-Z0-9._%-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b/i当我运行测试时,我得到:失败:1)用户失败/错误:它{应该validate_format_of(:email).not_with('test@test')}当电子邮件设置为“test@test”时,预期错误包括“can'tbeblank”,得到错误

  10. ruby-on-rails - Rails 使用了哪些测试框架? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭9年前。ImprovethisquestionRails使用了哪些单元测试框架?我正在阅读一本书(PragmaticProgrammersAgileDev.withRails),其中展示了如何在Rails中进行单元测试。这本书向我展示了默认的Rails测试套件(Test::Unit的子类)。这是Rails社区中使用的主要测试框架吗?我在执行常规ruby​​时使用RSpec,我也希望能够在Rails中使用它(如果不是太麻烦的话)?

随机推荐