Loading multiple versions of the same class

前端 未结 3 1639
一整个雨季
一整个雨季 2020-12-17 01:05

Let\'s say I release a code library as a standalone PHP class. Someone then uses version 1.0 of that library in their application. Later, I release version 2.0 of the libr

3条回答
  •  失恋的感觉
    2020-12-17 01:38

    I decided on a slightly alternate route. The namespace method works, but you need a different namespace for each version of the class. So it's not really scalable, because you have to pre-define the number of available namespaces.

    Instead, I've settled on a specific naming schema for the classes and a version loader/instantiater.

    Each class will take the following format:

    The parent My_Library class will actually end up containing a few identifiers specific to the library - purpose, compatibility statements, etc. That way I can perform other logical checks to make sure the right My_Library exists before moving forward and claiming that My_Library_1_0 is really version 1.0 of the library I want.

    Next, I have a loader class that I'll be using in my main project:

    Once this is done, you can use Loader to load both instances of the class or simple references if you want to use static methods:

    $reference = Loader::load( 'library.php', 'My_Library', '1.0' );
    
    $loader = new Loader();
    $instance = $loader->load( 'library.php', 'My_Library', '1.0' );
    

    Not quite the same as the namespace version I was shooting for, but it works and alleviates my concerns about breaking things for the end user. I am assuming that two different versions of My_Library_1_0 would be the same, though ... so there's still a dependence on third party developers knowing what they're doing.

提交回复
热议问题