Получение ServiceNotFoundException при маршрутизации из подробного руководства

Я сделал все учебники по Zend Framework 2, останавливаясь на «маршрутизации», именно так: https://docs.zendframework.com/tutorials/in-depth-guide/understanding-routing/

Моя проблема в том, что я сделал все в своем коде, как было предложено, но я сталкиваюсь с этой ошибкой, когда пытаюсь использовать маршрут в своем локальном http://localhost:8080/blog, доступном после запуска php -S 0.0.0.0:8080 -t public public/index.php:

Неустранимая ошибка: необработанное исключение «Zend\ServiceManager\Exception\ServiceNotFoundException» с сообщением «Подключаемый модуль с именем «Блог\Сегмент» не найден в диспетчере подключаемых модулей Zend\Router\RoutePluginManager» в C:_PROJETOS\Knowledge\ZendFramework2\5. -InDepth\vendor\zendframework\zend-servicemanager\src\AbstractPluginManager.php:131 Трассировка стека: #0 C:_PROJETOS\Knowledge\ZendFramework2\5-InDepth\vendor\zendframework\zend-router\src\SimpleRouteStack.php(280 ): Zend\ServiceManager\AbstractPluginManager->get('Блог\Сегмент', Массив) #1 C:_PROJETOS\Knowledge\ZendFramework2\5-InDepth\vendor\zendframework\zend-router\src\Http\TreeRouteStack.php(201 ): Zend\Router\SimpleRouteStack->routeFromArray(Array) #2 C:_PROJETOS\Knowledge\ZendFramework2\5-InDepth\vendor\zendframework\zend-router\src\Http\TreeRouteStack.php(151): Zend\Router\ Http\TreeRouteStack->routeFromArray(Array) #3 C:_PROJETOS\Knowledge\ZendFramework2\5-InDepth\vendor\zendframework\zend-router\src\SimpleRouteStack.php(142): Zend\Router\Http \TreeRouteStack->addRoute('deta в C:_PROJETOS\Knowledge\ZendFramework2\5-InDepth\vendor\zendframework\zend-servicemanager\src\AbstractPluginManager.php в строке 131

Я не вижу, что происходит для решения проблемы, к сожалению, я долгое время не программировал с Zend Framework 2.

Я очень благодарен за любую помощь в понимании и решении этого!

Мой модуль называется «Блог», и в нем находятся мои файлы:

модуль.config.php

<?php
namespace Blog;

use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;

return [
    'service_manager' => [
        'aliases' => [
            //Model\PostRepositoryInterface::class => Model\PostRepository::class
            Model\PostRepositoryInterface::class => Model\ZendDbSqlRepository::class,
        ],
        'factories' => [
            Model\PostRepository::class => InvokableFactory::class,
            Model\ZendDbSqlRepository::class => Factory\ZendDbSqlRepositoryFactory::class,
        ],
    ],
    'controllers' => [
        'factories' => [
            Controller\ListController::class => Factory\ListControllerFactory::class,
        ],
    ],
    'router' => [
        'routes' => [
            'blog' => [
                'type' => Literal::class,
                'options' => [
                    'route'    => '/blog',
                    'defaults' => [
                        'controller' => Controller\ListController::class,
                        'action'     => 'index',
                    ],
                ],
                'may_terminate' => true,
                'child_routes'  => [
                    'detail' => [
                        'type' => Segment::class,
                        'options' => [
                            'route'    => '/:id',
                            'defaults' => [
                                'action' => 'detail',
                            ],
                            'constraints' => [
                                'id' => '[1-9]\d*',
                            ],
                        ],
                    ],
                ],
            ],
        ],
    ],
    'view_manager' => [
        'template_path_stack' => [
            __DIR__ . '/../view',
        ],
    ],
];

СписокКонтроллер.php

<?php
namespace Blog\Controller;

use Blog\Model\PostRepositoryInterface;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use InvalidArgumentException;

class ListController extends AbstractActionController
{
    /**
     * @var PostRepositoryInterface
     */
    private $postRepository;

    public function __construct(PostRepositoryInterface $postRepository)
    {
        $this->postRepository = $postRepository;
    }

    public function indexAction()
    {
        return new ViewModel([
            'posts' => $this->postRepository->findAllPosts(),
        ]);
    }

    public function detailAction()
    {
        $id = $this->params()->fromRoute('id');

        try {
            $post = $this->postRepository->findPost($id);
        } catch (\InvalidArgumentException $ex) {
            return $this->redirect()->toRoute('blog');
        }

        return new ViewModel([
            'post' => $post,
        ]);
    }
}

ZendDbSqlRepository.php

<?php
namespace Blog\Model;

use InvalidArgumentException;
use RuntimeException;
use Zend\Hydrator\HydratorInterface;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Db\Sql\Sql;

class ZendDbSqlRepository implements PostRepositoryInterface
{
    /**
     * @var AdapterInterface
     */
    private $db;

    /**
     * @var HydratorInterface
     */
    private $hydrator;

    /**
     * @var Post
     */
    private $postPrototype;

    public function __construct(
        AdapterInterface $db,
        HydratorInterface $hydrator,
        Post $postPrototype
    ) {
        $this->db            = $db;
        $this->hydrator      = $hydrator;
        $this->postPrototype = $postPrototype;
    }

    /**
    * Return a set of all blog posts that we can iterate over.
    *
    * Each entry should be a Post instance.
    *
    * @return Post[]
    */
    public function findAllPosts()
    {
        $sql       = new Sql($this->db);
        $select    = $sql->select('posts');
        $statement = $sql->prepareStatementForSqlObject($select);
        $result    = $statement->execute();

        if (! $result instanceof ResultInterface || ! $result->isQueryResult()) {
            return [];
        }

        $resultSet = new HydratingResultSet($this->hydrator, $this->postPrototype);
        $resultSet->initialize($result);
        return $resultSet;
    }

    /**
     * {@inheritDoc}
     * @throws InvalidArgumentException
     * @throws RuntimeException
     */
    public function findPost($id)
    {
        $sql       = new Sql($this->db);
        $select    = $sql->select('posts');
        $select->where(['id = ?' => $id]);

        $statement = $sql->prepareStatementForSqlObject($select);
        $result    = $statement->execute();

        if (! $result instanceof ResultInterface || ! $result->isQueryResult()) {
            throw new RuntimeException(sprintf(
                'Failed retrieving blog post with identifier "%s"; unknown database error.',
                $id
            ));
        }

        $resultSet = new HydratingResultSet($this->hydrator, $this->postPrototype);
        $resultSet->initialize($result);
        $post = $resultSet->current();

        if (! $post) {
            throw new InvalidArgumentException(sprintf(
                'Blog post with identifier "%s" not found.',
                $id
            ));
        }

        return $post;
    }
}

ZendDbSqlRepositoryFactory.php

<?php
namespace Blog\Factory;

use Interop\Container\ContainerInterface;
use Blog\Model\Post;
use Blog\Model\ZendDbSqlRepository;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Hydrator\Reflection as ReflectionHydrator;
use Zend\ServiceManager\Factory\FactoryInterface;

class ZendDbSqlRepositoryFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        return new ZendDbSqlRepository(
            $container->get(AdapterInterface::class),
            new ReflectionHydrator(),
            new Post('', '')
        );
    }
}

PostRepositoryInterface.php

<?php
namespace Blog\Model;

interface PostRepositoryInterface
{
    /**
     * Return a set of all blog posts that we can iterate over.
     *
     * Each entry should be a Post instance.
     *
     * @return Post[]
     */
    public function findAllPosts();

    /**
     * Return a single blog post.
     *
     * @param  int $id Identifier of the post to return.
     * @return Post
     */
    public function findPost($id);
}

Post.php

<?php
namespace Blog\Model;

class Post
{
    /**
     * @var int
     */
    private $id;

    /**
     * @var string
     */
    private $text;

    /**
     * @var string
     */
    private $title;

    /**
     * @param string $title
     * @param string $text
     * @param int|null $id
     */
    public function __construct($title, $text, $id = null)
    {
        $this->title = $title;
        $this->text = $text;
        $this->id = $id;
    }

    /**
     * @return int|null
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getText()
    {
        return $this->text;
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }
}

index.phtml

<h1>Blog</h1>

<?php foreach ($this->posts as $post): ?>
    <article>
        <h1 id="post<?= $post->getId() ?>"><?= $post->getTitle() ?></h1>

        <p><?= $post->getText() ?></p>
    </article>
<?php endforeach ?>

person RPichioli    schedule 30.12.2016    source источник


Ответы (1)


В вашем module.config.php отсутствует следующее пространство имен:

use Zend\Router\Http\Segment;

Вот почему он пытается искать Blog\Segment, поскольку вы забыли использовать правильное пространство имен для Segment::class и, таким образом, ищете класс в текущем пространстве имен.

person Kwido    schedule 30.12.2016
comment
Спасибо за помощь @Kwido, отсутствовала ссылка на сегмент! Я пытался, но ошибка не устранена. Я обновил свой код и разместил сообщение об ошибке полным сообщением. - person RPichioli; 30.12.2016
comment
Я просмотрел свой код, и теперь он работает, спасибо за решение и объяснение! - person RPichioli; 31.12.2016