V
V
Vit2015-06-09 20:52:04
Laravel
Vit, 2015-06-09 20:52:04

How to create a class with a factory method?

In Laravel I have the following classes:

<?php namespace App\Models;
use Illuminate\Support\Str;

interface IParser {
  public function get();
}

class ParserFactory {
  public static function create($engine)
  {
    $class = Str::title($engine) . 'Parser';
    return new $class;
  }
}

class FirstParser implements IParser {
  public function get()
  {
    echo 1;
  }
}

I create a class like this:
$engine = 'first';
$parser = ParserFactory::create($engine);

As a result, I get an error:
FatalErrorException in Parser.php line 14: Class 'FirstParser' not found

If you write in a factory method:
public static function create($engine)
{
  $class = new FirstParser();
  return $class;
}

That all works, the class is created. I don't understand why using new $class doesn't work either?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Damir Makhmutov, 2015-06-09
@reech

You need to specify the full path to the class, along with the namespace;

$class = 'App\\Models\\' . Str::title($engine) . 'Parser';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question