0

I am developing an object to interface with an API. Some calls to the API require authentication and others do not. In terms of best practice, should

a) The authentication method returns a token. The method is called from the controller just before a call to an api call/method that needs authentication and the token is passed in as a parameter.

class api {
    public function auth() {
        .....
        return $token;
    }
    public function getInfo($token) {
        .....
    }

b) The authentication method sets a property of the class with token and you must remember to call the method before calling a method that needs auth

class api {
    private $token;
    public function auth() {
        .....
        $this->token = $token;
    }
    public function getInfo() {
        $token = $this->token;
        .....
    }

c) Methods that need auth call to auth method themselves

class api {
    private $token;
    public function auth() {
        .....
        return $token;
    }
    public function getInfo() {
        $token = $this->auth();
        .....
    }

I suppose the above could have a cached auth as a property to save unnecessary calls to auth api call.

Or any other way? Just looking for which is the best practice for such an object and why. Thanks in advance!

Mark
  • 5,045
  • 11
  • 43
  • 59

2 Answers2

2

"c" is the way to go.

No other object needs to know which method needs authentiaction and which doesn't.

Infact... your auth() method shouldn't even be public and the credentials "user, pass" should pe passed through the constructor in the api class.

see: http://en.wikipedia.org/wiki/Separation_of_concerns

Udan
  • 5,213
  • 1
  • 26
  • 34
1

From the three awailable, the option A is the better one, if you look at it from viewpoint of long term maintainability. It's because you should test all your public methods. Passing value directly, instead of making internal call to a public method, makes it as lot easier to write unit-tests for that particular class.

That said, authentication would usually be it's own thing, instead of being part of class, which also does other things, as describes in this post. The methods in your example make me suspect, that you are violating SRP.

Update

Now that I thought of it, having a class, where one public method has another public method as a dependency, might be considered a code smell, that is associated with SRP violation.

Community
  • 1
  • 1
tereško
  • 56,151
  • 24
  • 92
  • 147