doumei1203 2018-05-07 13:22
浏览 69

Laravel的多态性?

for example I have model Message with these columns:

messages
- id
- body
- type
- created_at
- updated_at

And such a controller:

class MessageController extends Controller
{

    /**
     * Display the specified resource.
     *
     * @param  \App\Message  $message
     * @return \Illuminate\Http\Response
     */
    public function show(Message $message)
    {
        switch ($message->type) {
            case 'info':
                $color = 'blue';
                // updated - lots of code here!
                break;
            case 'warning':
                $color = 'yellow';
                // updated - lots of code here!
                break;

            .
            .
            .

            case 'danger':
                $color = 'red';
                // updated - lots of code here!
                break;
            default:
                $color = 'gray';
                // updated - lots of code here!
        }
        return view('messages.show',compact(['message','color']));
    }

}

and as you see my problem is this long switch. I tried searching and I found that Polymorphism could help me to avoid this long switch, but I did not find out how to implement it how much I went and all my searches ended in Polymorphic Relations in Laravel that was not my answer.

would you help me to do something like this:

class MessageController extends Controller
{

    /**
     * Display the specified resource.
     *
     * @param  \App\Message  $message
     * @return \Illuminate\Http\Response
     */
    public function show(Message $message)
    {
        $color = $message->[something?]->color();
        return view('messages.show',compact(['message','color']));
    }

}

Update: As I wrote at beginning, It's just an example and switch case block will contain more lines of code.

  • 写回答

4条回答 默认 最新

  • dongyi4170 2018-05-07 13:33
    关注

    No need to Polymorphic just make an array like this in your model or config:

        $messageColors = [
            "info"=>"blue",
            .......
        ]
    

    And then write this:

        $color = $messageColors[$message->type];
    
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?