7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-10-16

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

動作環境

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);

7
8
0

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
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?