mardi 10 octobre 2017

Dynamic class method name in php

I'm working on a project using graphql-php. There is an example which suggests creating a class like this:

use Project\CategoryType;
use Project\PageType;

class Types {


private static $page;
private static $category;

    public static function page() {
        return self::$page ?: (self::$page = new PageType());
    }

    public static function category() {
        return self::$category ?: (self::$category = new CategoryType());
    }
}

Later I can use this class methods like so:

Types::page() or Types::category()

This works fine. However, I think this is an anti-pattern and could be optimised. As the project grows, the number of similar functions and private class fields grows and this becomes inconvenient. Is there any way to refactor the class so I don't have to manually add a function for each type but still call the class methods as I do it now? (Types::page()).

Aucun commentaire:

Enregistrer un commentaire