在适当的位置移动复制代码并从所有控制器访问它们

时间:2014-08-31 12:24:56

标签: symfony

我希望能够从我的所有控制器访问代码,那么最好的方法是什么?下面的代码是处理表单错误,我一直在我的项目中的每个控制器中复制它。

所以我想在其他地方保留getErrorMessages()并在下面的控制器中访问它。

注意:我读到services,但感到困惑,this example

示例控制器:

class HelloController extends Controller
{
    public function processAction(Request $request)
    {
        //More code here

        if ($form->isValid() !== true)
        {
            $errors = $this->getErrorMessages($form);

            return $this->render('SayHelloBundle:hello.html.twig',
                    array(
                        'page' => 'Say Hello',
                        'form' => $form->createView(),
                        'form_errors' => $errors
                    ));
        }

        //More code here
    }

    private function getErrorMessages(FormInterface $form)
    {
        $errors = array();

        foreach ($form->getErrors() as $error)
        {
            $errors[] = $error->getMessage();
        }

        foreach ($form->all() as $child)
        {
            if (! $child->isValid())
            {
                $options = $child->getConfig()->getOptions();
                $field = $options['label'] ? $options['label'] : $child->getName();
                $errors[$field] = implode('; ', $this->getErrorMessages($child));
            }
        }

        return $errors;
    }
}

2 个答案:

答案 0 :(得分:0)

您可以创建一个包含所有基本操作的类,并在控制器中调用该类(或类集)。

答案 1 :(得分:0)

确定没错:)

<强> /var/www/html/local/sport/app/config/config.yml

imports:
    - { resource: services.yml }

<强> /var/www/html/local/sport/app/config/services.yml

parameters:
    form_errors.class: Football\TeamBundle\Services\FormErrors

services:
    form_errors:
        class:  %form_errors.class%

<强> /var/www/html/local/sport/src/Football/TeamBundle/Services/FormErrors.php

namespace Football\TeamBundle\Services;

use Symfony\Component\Form\FormInterface;


class FormErrors
{
    public function getErrors(FormInterface $form)
    {
        $errors = array();

        //This part get global form errors (like csrf token error)
        foreach ($form->getErrors() as $error)
        {
            $errors[] = $error->getMessage();
        }

        //This part get errors for form fields
        foreach ($form->all() as $child)
        {
            if (! $child->isValid())
            {
                $options = $child->getConfig()->getOptions();
                $field = $options['label'] ? $options['label'] : ucwords($child->getName());
                //There can be more than one field error, that's why implode is here
                $errors[strtolower($field)] = implode('; ', $this->getErrors($child));
            }
        }

        return $errors;
    }
} 

<强>控制器

if ($form->isValid() !== true) {
    $errors = $this->get('form_errors')->getErrors($form);
    echo '<pre>'; print_r($errors); exit;
}