LoginSignup
3
1

More than 5 years have passed since last update.

call_user_func_arrayを使った共通処理作成

Last updated at Posted at 2016-12-08

例えば、ある処理内で外側の処理を共通化させたいという場合がある。
トランザクションとか。これは例外処理内でbeginとcommitで挟みこむという形をとり、内の処理はそれぞれ異なる。
このトランンザクションを共通化させるときには高階関数とcall_user_func_arrayを使う。
トランザクション処理内で関数を可変関数として実行させることで、トランザクションを共通化して使える。
ただ、問題になるのは引数。

関数は可変関数として動的に実行できるが、引数の数は各関数固定になっている。
この問題を解決するのがcall_user_func_array。これはコールバック関数の実行時に引数を配列で渡すことが可能。
配列で渡すと、トランザクション処理内では、引数の数を気にする必要がないので、そのまま渡すだけで良い。

    private function transaction($func, array $args ) {

        try {
            $this->instance->beginTransaction();

            call_user_func_array([$this,$func], $args);

            $this->instance->commit();
        } catch(Execption $e) {
            $this->instance->rollBack();
        }
        return;
    }

    public function register() {
        $this->transaction('regist', [$parent_id, $child_id]);
    }

    public function updater() {
        $this->transaction('update', [$parent_id, $child_id, $title]);//引数の数が違っても大丈夫
    }

3
1
2

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
3
1