如何分开功能并将其称为php

时间:2016-04-26 16:06:44

标签: php model-view-controller symfony controllers

我在symfony 2中有一个项目......我有这个问题。

我有这个文件 src / ApiV1Bundle / Controller / TeamsController.php 女巫有这样的内容:

 <?php

namespace ApiV1Bundle\Controller;

use AppBundle\Entity\Teams;
use ApiV1Bundle\Collection\TeamsCollection;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Cocur\Slugify\Slugify;

Class TeamsController extends Controller
{
    /**
     * Lists all Teams entities.
     *
     */
    public function getTeamsAction()
    {

        $em = $this->getDoctrine()->getManager();

        $teams = $em->getRepository('AppBundle:Teams')->findBy(['active' => 1]);
        $resource = [];

        foreach ($teams as $team) {
            array_push($resource, $this->displayTeam($team));
        }

        $response = new Response(json_encode($resource));

        $response->setStatusCode(200);
        $response->headers->set('Content-Type', 'application/json');

        return $response;
    }

    function displayTeam(Teams $team)
    {
        $slug = new Slugify();

        $resource['id'] = $team->getId();
        $resource['name'] = $team->getName();
        $resource['slug'] = $slug->slugify($team->getName());
        $resource['league'] = $slug->slugify($team->getLeagueId());
        $resource['shield'] = $slug->slugify($team->getMultimediaId());

        return $resource;
    }

}

这完全有效......但我需要将辅助功能分开到主代码......在这样的文件中。

这是路线: src / ApiV1Bundle / Collection / TeamCollection.php ,内容如下:

<?php

namespace ApiV1Bundle\Collection;

use AppBundle\Entity\Teams; use Cocur\Slugify\Slugify;

Class TeamsCollection {

    function displayTeam(Teams $team)
    {
        $slug = new Slugify();

        $resource['id'] = $team->getId();
        $resource['name'] = $team->getName();
        $resource['slug'] = $slug->slugify($team->getName());
        $resource['league'] = $slug->slugify($team->getLeagueId());
        $resource['shield'] = $slug->slugify($team->getMultimediaId());

        return $resource;
    }
 }

这样可以保持控制器文件更干净,但我不知道在我的驱动程序中将这个新文件称为什么,或者我是否创建好,或者是否缺少某些东西。

1 个答案:

答案 0 :(得分:0)

这是我的建议:

use ApiV1Bundle\Collection\TeamsCollection;

public function getTeamsAction()
{
    $em = $this->getDoctrine()->getManager();

    $teams = $em->getRepository('AppBundle:Teams')->findBy(['active' => 1]);
    $resource = $team->map(function($team) {
        return TeamsCollection::displayTeam($team)
    };

    $response = new JsonResponse($resource);

    return $response;
}

在这种情况下,您必须使displayTeam成为静态函数。或者,您可以这样做:

$teamcollection = new TeamCollection();
return $teamcollection->displayTeam($team);

作为奖励,我提出了另外两条建议:

  • 使用JsonResponse而不是Response。在这种情况下,您不必设置Content-Type。不需要将StatusCode设置为200:它是默认状态。
  • 使用ArrayCollection::map。这是一个很棒的功能,但(不幸的是)它不是很受欢迎。