Joseph
Joseph

Reputation: 2712

Making functions within a class DRY in PHP

I'm using CakePHP and have created a class as follows:

class ApiController extends AppController {
    // functions
}

I have about 10 functions in the class and I have found that I have repeated myself with the exact 3 same lines of code at the beginning of every function:

if ($this->request->is('post')) {
    $data = $this->request->input('json_decode',true);
    $authUser = explode('.',$_SERVER['PHP_AUTH_USER']);
    $location_id = $authUser[1];
    // Rest of my function
}

Is there any way that I can create something in the class which runs those 3 lines of code first, and then makes the $data and $location_id variables available for my functions to use, or must I write those 3 lines for every function?

Upvotes: 0

Views: 169

Answers (2)

Elon Than
Elon Than

Reputation: 9775

It can be done using private method.

private $data = null;
private $locationId = null;
public function __construct($request = null, $response = null) {
    parent::__construct($request = null, $response = null);
    $this->data = $this->request->input('json_decode',true);
    $authUser = explode('.',$_SERVER['PHP_AUTH_USER']);
    $this->locationId = $authUser[1];
}

and then use it like this

$this->locationId;

Upvotes: 2

TheOnly92
TheOnly92

Reputation: 1763

You can write a method and put the 2 variables as a property of the class.

e.g.

class ApiController {
    private $location_id;
    private $data;

    private function init() {
        // ...
    }
}

And then access the variables by doing $this->location_id.

Upvotes: 1

Related Questions