LoginSignup
23
17

More than 3 years have passed since last update.

LaravelでもOptional Chainを使いたい、使おう。

Last updated at Posted at 2017-10-09

TL;DR

  • Laravel5.5からoptional機能が追加されたが、そのまま使うとchainができない
  • laravelのmacroを加えてやることでoptional chainチックな動きができる。
  • Viewでのぬるぽからついに解放される!

Laravelのオプショナル機能

Laravel5.5からオプショナルの様なものが利用できるようになりました!

これでViewでのヌルポから解放される!と思ったんですが、どうやらOptionalChainできるわけじゃないみたいです。

ただ、こちらの記事(Laravel 5.5 で導入された Optional クラスについて)にも有りますように、
大元のOptionalClassはmacroが追加できる様になってます。

macroを使ってoptionalChainっぽい動きができないかな、と思っていじってみたら
案外すぐできたので、僕がやったやり方を下でシェアさせていただきます。

macro追加部分のコード

AppServiceProviderをちょちょっといじってみます。


<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Optional;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        Optional::macro('chain', function (string $property) {
            return (is_object($this->value)) ? optional($this->value->$property) : optional(null);
        });
    }
}

実際に使ってみた



class Address{
    public $zip;

    public function __construct($zip = null){
       $this->zip = $zip;
    }
}

class Customer{
    public $address;

    public function __construct(Address $address){
        $this->address = $address;
    }
}

// Zip実際にあるバージョン
$customerWithZip = new Customer(new Address('xxx-xxxx'));
$zip = optional($customerWithZip)->chain('address')->zip ?? '登録してね☆';
// -> 'xxx-xxxx'

// Zipないバージョン
$customerWithoutZip = new Customer(new Address());
$zip = optional($customerWithoutZip)->chain('address')->zip ?? '登録してね☆';
// -> '登録してね☆'

おもったよりも使いやすい!

まとめ

  • chainMacroが思ったよりも便利で会社でアップデート時に実戦投入できそう。
  • PHPの言語仕様としてのオプショナルの採用は多分ないだろう。
23
17
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
17