简体   繁体   English

如何在Laravel雄辩的类中添加自定义方法

[英]How to add custom method in laravel eloquent class

I want to add some specific custom method to Laravel Eloquent so that I can access those method from any Modal. 我想向Laravel Eloquent添加一些特定的自定义方法,以便可以从任何Modal访问这些方法。

Like 喜欢

class Bar extends Eloquent
{
    public $table = 'mytable';

    public function foo($log_table)
    {
        self::checkAndCreateLogTable($log_table); //<-- this 'll be a custom function defined in Eloquent
    }

}

I have one solution that is to create a base class and extend Eloquent and then extend the new class from all the modal like this 我有一个解决方案是创建一个基类并扩展Eloquent,然后从所有模态扩展新类,如下所示

class Foo extends Eloquent
{

    public function checkAndCreateLogTable($log_table)
    {
        //get the table name from the modal and do some stuff
    }

}

class Bar extends Foo
{

}

Is there any better solution then this? 有没有更好的解决方案呢?

If the method checkAndCreateLogTable will be used in literally every model you create (also in future), it would be easier to create a class that extends the Eloquent class. 如果方法checkAndCreateLogTable将在您创建的每个模型中使用(以及将来),则创建扩展Eloquent类的类将更加容易。

If not you should create a trait . 如果没有,您应该创建一个trait Eg: 例如:

trait HasLogTable
{
    public function checkAndCreateLogTable ($log_table)
    {
        // Get the table name from the model and do some stuff
    }
}

class Bar extend Eloquent
{
    use HasLogTable;
}

However if this is only a one time task at the beginning of you application installation I would create a console command (or migration seen the name of the method?). 但是,如果在应用程序安装开始时这只是一次任务,那么我将创建一个控制台命令(或迁移是否看到了方法的名称?)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM