Php namespace interface

I have PHP simple skeleton project, with folder structures like this:

Project/
           /Source
                       /Contract
                                     /IContract.php
          /ProductOne
                      /Product1.php
          index.php // index is in the same level as Source, in root

Inside IContract.php I have:

<?php 
namespace Source\Contract;

interface IContract {
    public function someView();
}

Inside Source->ProductOne->Product1.php I created class Product1:

namespace Source\ProductOne;
use Source\ProductOne\IContract;

class Product1 implements IContract {
    // logic

Fatal error : Interface ‘Source\ProductOne\IContract’ not found in

So, how to namespace that interface inside my Product1 class? Should I use require statement inside class Product1? Because using namespaces and require doesn’t look good

Hope somebody understands me.

use Source\Contract\IContract;

That is your interface.

And actually, in web-root should be only files that need access from web (index.php, .css, .js, images). So, I recommend you to change your project structure.

You right about index.php, but use Source\Contract\IContract; doesn’t work

What is your autoloading mechanism?

I didn’t use composer or spl_autoload_function, yet. I required classes in index.php

Show this requirements, please.

It is up to you to explicitly require all the files needed including your interfaces. You also have an error in your product file.

# Source/ProductOne/Product1.php
namespace Source\ProductOne;
use Source\Contract\IContract; // *** Had the wrong namespace
class Product1 implements IContract {
    public function someView() {
    }
}

# index.php
require_once './Source/Contract/IContract.php';
require_once './Source/ProductOne/Product1.php';

$product = new \Source\ProductOne\Product1();
$product->someView();

There are variations. You could for example require the interface file from inside of whichever files implement the interface. But it quickly becomes a big mess.

If you want, I can post a very simple example of how to use the composer autoloader to eliminate the require statements. Really no reason not to use it.

1 Like

Thanks!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.