Предотвращение дублирования кода в моделях в Laravel - PullRequest
0 голосов
/ 20 сентября 2019

У меня есть две разные модели (ErrorLog и EntityLog) с похожим кодом, как я могу предотвратить это?EntityLog имеет следующий код:

class EntityLog extends Model
{
    protected const ACTION = 'action';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'entity', 'type', 'icon', 'action', 'action_detail', 'action_user_id'
    ];

    protected $with = ['action_user'];

    public function action_user()
    {
        return $this->belongsTo('App\User', Config::get('constants.LOGGING.ACTION_USER_ID'));
    }

    /**
     * Create Entity log
     *
     * @param $type
     * @param array $info
     * @return mixed
     */
    public static function add($type, $info)
    {
        $entity = $info['entity'];
        $entity_id = $info['entity_id'] ?? '';
        $action_user_id = $info['action_user_id'] ?? auth()->user()->id ?? Config::get('constants.SYSTEM_ADMIN');
        $action_detail = $info['action_detail'] ?? '';

        switch ($type){
            case 'create':
                $icon = 'fa-plus bg-purple';
                $action = $info[self::ACTION] ?? 'created successfully';
                break;
            case 'update':
                $icon = 'fa-pencil bg-teal';
                $action = $info[self::ACTION] ?? 'updated successfully';
                break;
            case 'delete':
                $icon = 'fa-trash bg-red';
                $action = $info[self::ACTION] ?? 'deleted successfully';
                break;
            default:
                $icon = $action = 'invalid_flag';
        }

        Log::info($type.' : '.$entity.' : '.$entity_id.' : '.$action.' : '.$action_detail.' : '.$action_user_id);
        return self::create([
            Config::get('constants.LOGGING.ENTITY') => $entity,
            Config::get('constants.LOGGING.ENTITY_ID') => $entity_id,
            Config::get('constants.LOGGING.TYPE') => $type,
            Config::get('constants.LOGGING.ICON') => $icon,
            Config::get('constants.LOGGING.ACTION') => $action,
            Config::get('constants.LOGGING.ACTION_DETAIL') => $action_detail,
            Config::get('constants.LOGGING.ACTION_USER_ID') => $action_user_id,
        ]);

    }
}

, а класс ErrorLog имеет следующий код:

class ErrorLog extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'entity', 'type', 'icon', 'action', 'action_detail', 'action_user_id'
    ];

    protected $with = ['action_user'];

    public function action_user()
    {
        return $this->belongsTo('App\User', Config::get('constants.LOGGING.ACTION_USER_ID'));
    }

    /**
     * Create Error log
     *
     * @param $type
     * @param array $info
     * @return mixed
     */
    public static function add($type, $info)
    {
        $entity = $info['entity'];
        $entity_id = $info['entity_id'] ?? '';
        $action_user_id = $info['action_user_id'] ?? auth()->user()->id ?? Config::get('constants.SYSTEM_ADMIN');
        $action_detail = $info['action_detail'] ?? '';

        switch ($type){
            case 'create':
                $icon = 'fa-plus bg-purple';
                $action = 'failed creating';
                break;
            case 'update':
                $icon = 'fa-pencil bg-teal';
                $action = 'failed updating';
                break;
            default:
                $icon = $action = 'invalid_flag';
        }

        Log::error($type.' : '.$entity.' : '.$entity_id.' : '.$action.' : '.$action_detail.' : '.$action_user_id);
        return self::create([
            Config::get('constants.LOGGING.ENTITY') => $entity,
            Config::get('constants.LOGGING.ENTITY_ID') => $entity_id,
            Config::get('constants.LOGGING.TYPE') => $type,
            Config::get('constants.LOGGING.ICON') => $icon,
            Config::get('constants.LOGGING.ACTION') => $action,
            Config::get('constants.LOGGING.ACTION_DETAIL') => $action_detail,
            Config::get('constants.LOGGING.ACTION_USER_ID') => $action_user_id,
        ]);

    }
}

Я считаю, что могу использовать черты для решения этой проблемы, но примеры, которые я рассматриваю, просто называют простымифункции из черт.

Как бы $fillable, $with и функция action_user работали бы в случае черт.

Любая помощь действительно приветствуется, спасибо:)

1 Ответ

0 голосов
/ 20 сентября 2019

Я думаю, что лучшим решением было бы создание родительского класса, который содержит повторяющиеся свойства и методы.

abstract class LogModel extends Model
{
    protected $fillable = [
        'entity', 'type', 'icon', 'action', 'action_detail', 'action_user_id'
    ];

    protected $with = ['action_user'];

    public function action_user()
    {
        return $this->belongsTo('App\User', Config::get('constants.LOGGING.ACTION_USER_ID'));
    }

    // ...
}

Теперь пусть ваши модели журналов наследуют этот класс:

class ErrorLog extends LogModel
{
    // ...
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...