Skip to content

ClassHelper

Mistralys edited this page Jun 29, 2022 · 13 revisions

This helper class is designed to be static analysis and refactoring-friendly when working with dynamic class names and composer autoloading.

Dynamic class names

When building class names dynamically, refactoring becomes difficult, and returning a specific class instance means you have to do a lot of instanceof calls, throwing exceptions if the object is not what you expected. The class has two methods for this:

requireObjectInstanceOf

This method can be passed an object instance and the expected class name, and will throw an exception if the object is not an instance of this class. The return value is documented as returning an instance of that class for static analysis tools like PHPStan.

function getInstance() : ExpectedClassName
{
    $class = 'Example\Dynamically\Built\ClassName';

    return ClassHelper::requireObjectInstanceOf(
        ExpectedClassName::class,
        new $class()
    );
}

It is also designed to write more concise code, which is easy to read.

Composer class loader

In a Composer project, the method getClassLoader() will return an instance of Composer's ClassLoader class, for advanced functionality.

New here?

Have a look at the overview for a list of all helper classes available in the package.

Table of contents

Find the current page in the collapsible "Pages" list above, and expand the page, to view a table of contents.

Clone this wiki locally