我正在创建我的第一个Zend Framework2项目。我的页面提供了创建广告的选项。我现在想要提供为广告添加书签的选项。需要做的是,当您在广告的页面上时,该网站将检查您是否已登录,如果您是,它将检查该广告是否已经添加了书签并显示该消息,否则它将为您提供链接“将广告添加到您的书签”。当您未登录时也会显示此链接,如果您单击此处,则会将您重定向到登录页面。
无论如何,为了实现上述目标,我创建了一个View Helper,它由BookmarkAdvertFactory创建。我还创建了一个BookmarkAdvertService,它检查当前的Bookmark状态。为此,我需要UserId和AdvertId。
在我的module.php中,我注入了userEntity以便能够在BookmarkAdvertService中获取UserId,但现在我不确定如何从服务访问AdvertId。有人可以给我一个建议吗?
module.php
'Advert\BookmarkLink' => function ($sl) {
$entityManager = $sl->get('doctrine.entitymanager.orm_default');
//$advertId = '395';
$myService = new Service\BookmarkAdvertService($advertId);
$myService->setEntityManager($entityManager);
$repository = $entityManager->getRepository('Advert\Entity\Bookmark');
$myService->setRepository($repository);
$authService = $sl->get('zfcuser_auth_service');
$userEntity = $authService->getIdentity();
$myService->setUserEntity($userEntity);
return $myService;
},
public function getViewHelperConfig()
{
return array(
'factories' => array(
'displayBookmarkLink' => 'Advert\View\Helper\BookmarkAdvertFactory')
}
服务\ BookmarkAdvertService.php
namespace Advert\Service;
use Advert\Entity\Bookmark as BookmarkEntity;
use Advert\Repository\BookmarkRepository;
use Doctrine\ORM\EntityManager;
use Zend\Debug\Debug;
class BookmarkAdvertService
{
protected $location;
protected $userEntity;
public function __construct($advertId)
{
$this->advertId = $advertId;
}
public function setEntityManager(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
public function setRepository(BookmarkRepository $repository) {
$this->repository = $repository;
}
public function setUserEntity($userEntity)
{
$this->userEntity = $userEntity;
}
public function getUserEntity()
{
return $this->userEntity;
}
public function checkAdvertBookmarkStatus()
{
$userId = $this->getUserEntity()->getId();
$bookmarkStatus = $this->repository->getBookmarkStatus($this->advertId,$userId);
return $bookmarkStatus;
}
}
查看\助手\ BookmarkAdvertFactory.php
namespace Advert\View\Helper;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class BookmarkAdvertFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$locator = $serviceLocator->getServiceLocator();
$service = $locator->get('Advert\BookmarkLink');
$helper = new BookmarkAdvert($service);
return $helper;
}
}
查看\助手\ BookmarkAdvert.php
namespace Advert\View\Helper;
use Zend\View\Helper\AbstractHelper;
class BookmarkAdvert extends AbstractHelper
{
protected $service;
public function __construct($service)
{
$this->service = $service;
}
public function __invoke()
{
$bookmarkStatus = $this->service->checkAdvertBookmarkStatus();
return $this->render($bookmarkStatus);
}
public function render($bookmarkStatus)
{
return $this->getView()->render('advert/partial/bookmarklink', array('bookmarkStatus' => $bookmarkStatus));
}
}
答案 0 :(得分:0)
您需要将advertId传递给视图助手,视图助手可以将其传递给服务。