【问题标题】:Symfony2: Right usage of controllerSymfony2:控制器的正确使用
【发布时间】:2014-04-05 14:38:52
【问题描述】:

我正在构建几页应用程序。想问一下控制器的正确使用方法是什么?

每个页面都有一个控制器?或者将页面作为方法放在同一个控制器中?就我而言,我正在使用数据库,我真的无法将所有内容都保存在一种方法中。在这种情况下,我创建了 Helper 类,帮助我在那里保存和生成一些代码。

控制器:

class DefaultController extends Controller
{

    //main method that performs as page
    public function indexAction()
    {
        $helper = new IgnasHelper();
    $profile = $this->profileQuery($helper);

    return $this->render(
        'IgnasIgnasBundle:Default:index.html.twig',
        array('profile' => $profile)
        );
    }

    //method that returns database's data back to main index method
    public function profileQuery(IgnasHelper $helper)
    {
        $em = $this->getDoctrine()->getManager();
        $selectAll = array('p.id', 'p.first', 'p.last', 'p.birth', 'p.country', 'p.city', 'p.email');
        $profile = $em->createQueryBuilder()
            ->select($selectAll)
            ->from('IgnasIgnasBundle:Profilis', 'p')
            ->getQuery()
            ->getResult();

        return $helper->profileArray($profile);
    }
}

现在是 Helper 类:

public function profileArray(array $profile)
{
    $id = $profile[0]['id'];
    $first = $profile[0]['first'];
    $last = $profile[0]['last'];
    $birth = $profile[0]['birth'];
    $country = $profile[0]['country'];
    $city = $profile[0]['city'];
    $email = $profile[0]['email'];

    return array(
        'id' => $id,
        'first' => $first,
        'last' => $last,
        'birth' => $birth,
        'country' => $country,
        'city' => $city,
        'email' => $email,
    );
}

所以对于其他页面,我正在考虑制作另一个控制器来执行它。我是否正确使用了控制器?

【问题讨论】:

  • 对于你的 profileArray 函数,你只能做 return $profile[0];没有别的
  • 是的,你是对的,我会这样做的 :)

标签: php symfony controller


【解决方案1】:

也许你可以使用Symfony Doctrine Repositories

控制器是为特定操作而设计的:例如,在博客中,您可以拥有 ArticleController、CategoryController 等...

你可以在一个控制器中拥有多个方法,但如果方法具有相同的主题会更好。

<?php
class CategoryController extends Controller
{

    function indexAction() { }
    function listArticleAction($catID) { }
    function createAction($catID) { }
    function renameAction($catID) { }
    [...]
}

当您想在 profileQuery 函数中进行自定义查询时,您应该(必须?)使用学说存储库。 之后你可以做出类似的东西

<?php
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository("YourBundle:YourEntity");
$list = $repo->whateverYouWantToDo();

使用这种方式有两个主要好处:
- 首先是不要在错误的地方使用自定义查询来重载控制器。
- 第二个是您可以在应用程序中的任何位置使用存储库方法(例如在另一个 Bundle 中)

希望对你有所帮助。

【讨论】:

  • 我有点问控制器的正确用法,而不是数据库:)。我在这里看到了关于存储库的要点,但是如果我应该在同一个控制器中保留 1 页 = 1 个方法,或者 1 页 = 1 个控制器,我找不到答案。
  • 编辑过的帖子,告诉我 ;)*
  • 所以实际上我可以为每个页面创建一个单独的控制器,对吧? :)
  • 是的,它会很好,但是你会有很多控制器
猜你喜欢
  • 1970-01-01
  • 2011-11-06
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多