1

What are the best practices for extending a library in PHP?

I'm using the bshaffer OAuth2 library. In my code, I instantiate the library like this:

//// Start up the OAuth2 server
require_once('./oauth2-server-php/src/OAuth2/Autoloader.php');
OAuth2\Autoloader::register();

All of the OAuth2 classes are under the namespace starting like OAuth2\foo\bar. I am able to extend these classes without specifying a namespace for my own classes by giving them a unique name (which I prefer not to do). However, I would like to create my own namespace in order to keep the actual class names the same when extending them.

For instance, when I try to extend the Pdo class this way, it says 'class Pdo already instantiated'.

class Pdo extends OAuth2\Pdo {
}

So I tried it this way. In MyServer.php, I have:

<?php
  namespace MyNS;
  class Server extends OAuth2\Server {
  }
?>

But then I get an error that the class MyNS\OAuth2\Server does not exist. Obviously, it doesn't, and I don't think you can go 'up' a level with namespaces like you can with directories.

I've spent a fair amount of time reading the docs for PHP classes. I can extend the classes by renaming them (eg MyServer or MyPdo), but this seems messy and I feel like I should use my own name space. Or even MyNS\OAuth2 could work if I knew how to do it that way. Maybe I have to create my own autoloader for the classes (which I don't know how to do yet)?

Can someone please shine a light in my brain?

1 Answer 1

2

You were almost there with your own namespace - you just need an extra backslash \ to ensure that you are referring to the OAuth2 that is sitting in the global space. - i.e.

<?php
    namespace MyNS;
    class Server extends \OAuth2\Server {
        //               ^______________________ here
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Figures. The woes of programming, a single slash breaks everything. Thank you SO much. Namespaces have clicked in my brain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.