Skip to content

HasSingletonMethods

Kevin Upton edited this page Nov 30, 2017 · 1 revision

Have you ever wanted to just call a method once and have it stored in a value, to be accessed next time around.

Well that is what this method is all about.

How it works

Methods with a certain prefix, (default s, can be changed by protected $methodPrefix = 'prefix'), when called by property with the same name (just without the prefix); it will return the called method, having only run once.

Example

In this example, accessing runOnce will only ever return 1.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Kevupton\Ethereal\Traits\HasSingletonMethods;

/**
 * Class Example
 * @package App
 * @property int runOnce
 */
class Example extends Model
{
    use HasSingletonMethods;

    private $count = 0;

    public function sRunOnce ()
    {
        return ++$this->count;
    }
}
Clone this wiki locally