我如何在cakephp 3.7的控制器和单元中使用相同的方法? [英] How do I use the same method in both Controllers and Cells in cakephp 3.7?

查看:64
本文介绍了我如何在cakephp 3.7的控制器和单元中使用相同的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的AppController中有一个实用程序方法,我需要在

I have an utility method in my AppController, and I need to use that method inside a Cell (backend).

在两个地方都有使用相同方法的标准方法吗?我不想重复代码.

Is there a standard way to use the same method in both places? I don't want to duplicate code.

推荐答案

我认为在Cell和Controller之间没有共享功能的标准约定,这可能表明关注(但不一定!).我通常首先要确保此函数实际上是一个实用程序",并且一般来说最好不要以其他方式实现...

I don't think there's a standard convention for sharing functions between Cell's and Controllers, it could be a sign of bad separation of concerns (but not necessarily!). I'd generally first make sure that this function is actually a "utility" and not better implemented some other way in general...

话虽如此,共享功能可能有几种方法:

Cake本身将其实用程序类放置在 src/Utility 中,例如

Cake itself places it's utility classes in src/Utility, for example the Hash class. It doesn't explicitly list using this directory structure yourself in the docs for your own Utilities, but I'd assume it's where they'd suggest if they did.

将方法粘贴在Utility静态类中:

Stick the method in the Utility static class:

namespace App\Utility;

class Gravitar {
    public static function getUrl($username){
        // the function
    }
}

然后在每个位置(例如在Controller中)使用该名称空间引用它:

And then reference it with that namespace in each place, for example in the Controller:

namespace App\Controller;

use App\Utility\Gravitar;

class PeopleController {

    public function view(){
        // Normal view etc.

        // Call by 
        Gravitar::getUrl($username );
    }
}

选项B-创建特质

将功能粘贴在特征中.如果您无法使函数静态化,那么我只会这样做(如果您不能将其静态化,则可能是一个不好的信号,它可能不是真正的实用程序").

Option B - Create A Trait

Stick the function in a trait. I would ONLY do this if you can't make the function static (and it might be a bad sign if you can't, it's probably not a true "utility").

没有传统的地方可以表现出共同的特质.您可以将其与 src/Controller/Traits 中的其他Controller Traits一起放置,从那里在Cell中进行引用:

There's no conventional place to put a shared trait. You could potentially place it in with other Controller Traits in src/Controller/Traits, reference it from there in a Cell:

namespace App\View\Cell;

use App\Controller\Traits\GravitarTrait;

class PeopleCell {

    use GravitarTrait;

    public function display(){
        // Normal cell display function.

        // Call by direct reference
        $this->getUrl($username);
    }
}

这篇关于我如何在cakephp 3.7的控制器和单元中使用相同的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆