Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Not Returning Interface Instance PHP

I'm getting a weird error on a class that implements an interface.

Error:

Catchable fatal error: Argument 1 passed to MyApp\Library\Cache::__construct() must be an instance of MyApp\Contacts\CacheInterface, instance of MyApp\Driver\Cache\File given

File Class:

namespace MyApp\Driver\Cache;
use MyApp\Library\Config;
use MyApp\Contracts\CacheInterface;

class File implements CacheInterface {
    private $expire;

    public function __construct($expire, Config $config) {
        $this->expire = $expire;
        $this->config = $config;

        ... more code
    }
}

Cache Class:

namespace MyApp\Library;
use MyApp\Contacts\CacheInterface;

final class Cache {

    private $cache;

    public function __construct(CacheInterface $cache) {
        $this->cache = $cache;
    }

    ... more methods
}

Interface:

namespace MyApp\Contracts;
interface CacheInterface {

    public function get($key);
    public function set($key, $value);
    public function delete($key);
    public function flush_cache();
}

Implemented as a service in a Pimple Container like so:

$this->data['cache'] = function ($data) {
    switch ($data['config_cache_type_id']):
        case 'apc':
            $driver = new Apc($data['cache.time'], $data['config']);
            break;
        case 'mem':
            $driver = new Mem($data['cache.time'], $data['config']);
            $driver->connect();
            break;
        case 'file':
        default:
            $driver = new File($data['cache.time'], $data['config']);
            break;
    endswitch;

    return new Cache($driver);
};

Of course the 4 Driver and Cache classes are included with the use keyword before the container class.

I can't see what I'm missing I've done several other contracts in exactly the same procedure. Any ideas would be appreciated.

like image 742
Vince Kronlein Avatar asked Nov 10 '22 10:11

Vince Kronlein


1 Answers

In your File.class, can you try replacing:

use MyApp\Contracts\CacheInterface;

With

use MyApp\Contacts\CacheInterface;

And for your interface, use:

namespace MyApp\Contacts;
like image 184
Dave Chen Avatar answered Nov 14 '22 23:11

Dave Chen