Help us understand the problem. What is going on with this article?

PHPでメソッドチェーンを使う

More than 1 year has passed since last update.

画像アップロード系の記事を書いた時にメソッドチェーンで実装したら便利だったのでメモ代わりに投稿
利用する場合にコードが読みやすくなるので良いですね

動作環境

PHP 7.1.20
※たぶん5系全般でも動きます

クラスの作成

returnで自分自身を返せばOK(setterに実装すると使いやすい)

photoUploader.php
<?php

/**
 * Class PhotoUploader
 */
class PhotoUploader
{
    private $filesystem;
    private $path;

    /**
     * PhotoUploader constructor.
     * @param Filesystem $filesystem
     */
    public function __construct(Filesystem $filesystem)
    {
        $this->filesystem = $filesystem;
    }

    /**
     * @param $path
     * @return $this
     */
    public function setPath($path)
    {
        $this->path = $path;

        return $this;
    }

    /**
     * @return String
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * @param $file
     * @return bool
     */
    public function upload($file)
    {
        // upload処理
    }

利用サンプル

sample.php
<?php
$filesystem = new Filesystem();
$uploader = new PhotoUploader($filesystem)

$path = '/tmp/test.png'

// こんな感じで使う
$uploader->setPath($path)->upload($file);

nagi125
名古屋在住のエンジニア。 ユーザー企業で開発組織を作っていきたいなーと思いながら働いています。
up-wish
愛知で「住まいの窓口ハウスボカン」を7拠点展開。注文住宅やリフォームも自社で行っている。
https://www.housebokan.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした