如何重构这段 symfony 代码?

发布于 2024-08-23 03:33:31 字数 364 浏览 5 评论 0 原文

在action.class.php中:

$form = new NewsForm();
$form->setWidget('thumbnail', new sfWidgetFormSelect(array('choices' => $news['images'])));
$form->getWidget('summarize')->setDefault($news['summarize']);
$form->getWidget('title')->setDefault($news['title']);

其中$news是前面步骤生成的;

看起来很多余,如何重构呢?

In action.class.php:

$form = new NewsForm();
$form->setWidget('thumbnail', new sfWidgetFormSelect(array('choices' => $news['images'])));
$form->getWidget('summarize')->setDefault($news['summarize']);
$form->getWidget('title')->setDefault($news['title']);

Where $news is generated in previous steps;

It looks redundant,how to refactor it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蔚蓝源自深海 2024-08-30 03:33:31

那么,除非您在多个操作中使用相同的代码,否则您的代码并不是多余的。
为了使其可重用,您可以使用 options 参数“nofollow noreferrer”>表单构造函数并按如下方式更改表单:

class NewsForm extends ... {

    public function configure() {
        //Whatever you do here
        //....

        // if a news is set we configure certain fields
        if($news = $this->getOption('news', false)) {
            $this->setWidget('thumbnail', new sfWidgetFormSelect(array('choices' => $news['images'])));
            $this->setDefault('summarize', $news['summarize']);
            $this->setDefault('title', $news['title']);
        }
    }
}

您可以使用以下方式创建表单:

$form = new NewsForm(array(), array('news' => $news));

参考:sfForm - getOption

Well your code is not redunant until you use the same code in mutliple actions.
To make it reusable, you can make use of the options parameter in the the form constructor and change the form as follows:

class NewsForm extends ... {

    public function configure() {
        //Whatever you do here
        //....

        // if a news is set we configure certain fields
        if($news = $this->getOption('news', false)) {
            $this->setWidget('thumbnail', new sfWidgetFormSelect(array('choices' => $news['images'])));
            $this->setDefault('summarize', $news['summarize']);
            $this->setDefault('title', $news['title']);
        }
    }
}

The you can create the form with:

$form = new NewsForm(array(), array('news' => $news));

Reference: sfForm - getOption

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文