skip to Main Content

Im wondering if its possible to init a class from a ‘mapping’ in a PHP model.

For instance, in a model, if I map strings to class names in an array, can i then pass a string to map to a specific class and then initialise it, if that makes sense.

In my model if I have an array;

public const $mappingArray = [
  'first-string-name-here' => 'FirstClassName',
  'second-string-name-here' => 'SecondClassName',
];

Would it be possible to pass the string in a controller method and receive a class;

2

Answers


  1. Yes, it’s possible to create a mapping of strings to class names in PHP and then dynamically instantiate a class based on a string in a controller method. You can use PHP’s built-in class_exists() and new operators to achieve this.

    Here’s an example of how you can do it:

    In your model:

    class YourModel {
        public const $mappingArray = [
            'first-string-name-here' => 'FirstClassName',
            'second-string-name-here' => 'SecondClassName',
        ];
    }
    

    In your controller method:

    public function createInstanceFromClassString($classString) {
        if (array_key_exists($classString, YourModel::$mappingArray)) {
            $className = YourModel::$mappingArray[$classString];
    
            if (class_exists($className)) {
                return new $className();
            } else {
                // Handle the case where the class doesn't exist
                // You might want to throw an exception or return an error message
                return null;
            }
        } else {
            // Handle the case where the string is not in the mapping
            // You might want to throw an exception or return an error message
            return null;
        }
    }
    

    You can call the createInstanceFromClassString method in your controller, passing the string you want to map to a class:

    $className = $yourModelInstance->createInstanceFromClassString('first-string-name-here');
    if ($className) {
        // $className is now an instance of the mapped class
        // You can use it as needed
    } else {
        // Handle the error case
    }
    

    This way, you can dynamically create instances of classes based on the strings you provide, as long as they are mapped in your model’s mapping array.

    Login or Signup to reply.
  2. You can map strings to class names and then instantiate those classes dynamically in PHP. Here’s how you can achieve this:

    Define Your Classes:

    class FirstClassName {
     public function sayHello() {
        return "Hello from FirstClassName!";
     }
    }
    
    class SecondClassName {
     public function sayHello() {
        return "Hello from SecondClassName!";
     }
    }
    

    Model with Mapping Array:

    class Model {
     public const MAPPING_ARRAY = [
        'first-string-name-here' => 'FirstClassName',
        'second-string-name-here' => 'SecondClassName',
     ];
    }
    

    Controller Method to Instantiate Class:

    function instantiateClassFromMapping($stringKey) {
      if (isset(Model::MAPPING_ARRAY[$stringKey])) {
        $className = Model::MAPPING_ARRAY[$stringKey];
        if (class_exists($className)) {
            return new $className();
        } else {
            throw new Exception("Class {$className} does not exist.");
        }
    } else {
        throw new Exception("String key {$stringKey} not found in mapping.");
    }
    }
    

    Usage:

    try {
        $instance = instantiateClassFromMapping('first-string-name-here');
        echo $instance->sayHello();  // Outputs: Hello from FirstClassName!
    } catch (Exception $e) {
        echo $e->getMessage();
    }
    

    This way, you can map strings to class names in your model and then use those mappings to dynamically instantiate classes in your controller.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search