doujiao7325 2017-07-21 00:23
浏览 38

ZF - Doctrine2无法检索存储库

whats this wrong with this? I'm new in zend framework...........................................................................................................................

enter image description here

this is my folder struct

enter image description here

enter image description here

UserControllerFactory.php

<?php

namespace Admin\Controller\Factory;

use Admin\Controller\UserController;
use User\Entity\User;
use Admin\Form\UserForm;
use User\Model\UserTable;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Entity;
use Interop\Container\ContainerInterface;

class UserControllerFactory
{

    public function __invoke(ContainerInterface $container)
    {

        /** @var EntityManager $entityManager */
        $entityManager = $container->get(EntityManager::class);
        $repository = $entityManager->getRepository(User::class);
        $userForm = $container->get(UserForm::class);
        return new UserController($entityManager, $repository, $userForm);
    }


}

UserController.php

<?php

namespace Admin\Controller;

//use User\Entity\User;
use Admin\Form\UserForm;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
use Zend\Hydrator\ClassMethods;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Http\Request;
use Zend\View\Model\ViewModel;


class UserController extends AbstractActionController
{
    /**
     * @var EntityRepository
     */
    private $repository;
    /**
     * @var EntityManager
     */
    private $entityManager;
    private $form;

    public function __constructor(EntityManager $entityManager, EntityRepository $repository, UserForm $form){
        $this->form = $form;
        $this->repository = $repository;
        $this->entityManager = $entityManager;
    }

    public function indexAction()
    {    
        return new ViewModel([
            'users' => $this->repository->fetchAll()
        ]);
    }

      public function addAction()
    {
        $form = $this->form;
        $form->get('submit')->setValue('Adicionar');

        $request = $this->getRequest();

        if (!$request->isPost()) {
            return ['form' => $form];
        }

        $form->setData($request->getPost());

        if (!$form->isValid()) {
            return ['form' => $form];
        }

        $post = $form->getData();
        $this->entityManager->persist($post);
        $this->entityManager->flush();

        return $this->redirect()->toRoute('admin/user');

    }

    public function editAction()
    {
        $id = (int)$this->params()->fromRoute('id', 0);

        if (!$id || !($post = $this->repository->find($id))) {
            return $this->redirect()->toRoute('admin/user');
        }

        $form = $this->form;
        $form->bind($post);
        $form->get('submit')->setAttribute('value', 'Edit Post');

        $request = $this->getRequest();

        if (!$request->isPost()) {
            return [
                'id' => $id,
                'form' => $form
            ];
        }

        $form->setData($request->getPost());
        if (!$form->isValid()) {
            return [
                'id' => $id,
                'form' => $form
            ];
        }

        $this->entityManager->flush();
        return $this->redirect()->toRoute('admin/user');
    }

    public function deleteAction()
    {
        $id = (int)$this->params()->fromRoute('id', 0);

        if (!$id || !($post = $this->repository->find($id))) {
            return $this->redirect()->toRoute('admin/user');
        }

        $this->entityManager->remove($post);
        $this->entityManager->flush();
        return $this->redirect()->toRoute('admin/user');

    }
}

UserTable.php

<?php
/**
 * Created by PhpStorm.
 * User: jho
 * Date: 24/06/2017
 * Time: 18:55
 */

namespace User\Model\Factory;


use Zend\Db\Exception\RuntimeException;
use Zend\Db\TableGateway\TableGatewayInterface;
class UserTable
{
    private $tableGateway;

    public function find($id)
    {
        $id = (int)$id;
        $rowset = $this->tableGateway->select(['id' => $id]);
        $row = $rowset->current();

        if (!row) {
            throw new RuntimeException(sprintf(
                'Could not retrieve the row %d', $id
            ));
        }

        return $row;
    }

    public function fetchAll(){
        return $this->tableGateway->select();
    }

    public function save(User $user){
        $data = [
            'username'=>$user->username,
            'fullname'=>$user->fullname,
            'password'=>$user->password,
        ];

        $id = (int) $user->id;

        if((int)$user->id === 0){
            $this->tableGateway->insert($data);
            return;
        }

        if(!$this->find($id)){
            throw new RuntimeException(sprintf(
                'Could not retrieve the row %d', $id
            ));
        }
        $this->tableGateway->update($data, ['id'=>$id]);

    }
}

User.php

<?php


namespace User\Model;


class User
{
    public $id;
    public $fullname;

    public function exchangeArray(array $data){
        $this->id = (!empty($data['id'])) ? $data['id']: null;
        $this->title = (!empty($data['fullname'])) ? $data['fullname']: null;
    }

    public function getArrayCopy(){
        return[
            'id'=>$this->id,
            'fullname'=>$this->fullname,
        ];
    }
}
  • 写回答

1条回答 默认 最新

  • doutuan6158 2017-07-22 22:33
    关注

    You are mixing up two different approaches of retrieving data from your database.

    You can either use the Zend approach as in TableGateway's or you can go with Doctrine (EntityManager/Repositories).

    So you've got to make a choice between one of the methods you want to use within your controller.

    So if you want to stick with Doctrine, you could take a look at the following slides of Ocramius: http://ocramius.github.io/presentations/doctrine-orm-and-zend-framework-2/#/59

    So you pretty much have to update your User model:

    namespace User\Model;
    
    use Doctrine\ORM\Mapping AS ORM;
    
    /**
     * @ORM\Entity()
     */
    class User
    {
        /**
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         * @ORM\Column(type="integer")
         */
        public $id;
    
        /** @ORM\Column(type="string") */
        public $fullname;
    
        public function exchangeArray(array $data){
            $this->id = (!empty($data['id'])) ? $data['id']: null;
            $this->title = (!empty($data['fullname'])) ? $data['fullname']: null;
        }
    
        public function getArrayCopy(){
            return[
                'id'=>$this->id,
                'fullname'=>$this->fullname,
            ];
        }
    }
    

    Update the following file module.config.php of your User module and add the following to your configuration:

    array(
    'doctrine' => array(
      'driver' => array(
        'application_entities' => array(
          'class' =>'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
          'cache' => 'array',
          'paths' => array(__DIR__ . '/../src/User/Model')
        ),
        'orm_default' => array(
          'drivers' => array(
            'User\model' => 'application_entities'
          )
        ),
      )
    ),
    

    Notice that this requires the Doctrine-ORM-module. See: https://github.com/doctrine/DoctrineORMModule

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度