Domanda

This is my first time writing an application in PHP. I normally developer in Node or MVC4, if that helps any.

Here is my directory structure for this project:

-TestProject
 --BackgroundWorkers
  ---Worker1
  ----Repositories
   -----Worker1.php
--index.php
--SplClassLoader.php

The namespace in Worker1.php is Worker1\Repositories and the class name is Worker1.

I've attempted every combination of Namespace and Path I can think of, but here's an example:

<?php

 require_once("SplClassLoader.php");
 $loader = new SplClassLoader('Worker1\Repositories', 'TestProject/BackgroundWorkers/Worker1');
 $loader -> register();

 $r = new Worker1\Repositories\Worker1();
?>

What am I doing wrong?

È stato utile?

Soluzione

All the SplClassLoader does is append your namespace path, as directories, to the supplied directory defined in the loader.

so. given your example of: namespace: Worker1\Repositories

Then the directory path defined in the loader should be: TestProject/BackgroundWorkers.

Note: always supply the full disk path as the 'lookup' directory.

Here is a test file that shows the use. I use 'testmysql' rather than 'TestProject'.

<?php

require __DIR__. '/SplClassLoader.php';

var_dump(__DIR__);

$loader = new SplClassLoader('Worker1\Repositories', __DIR__.'/BackgroundWorkers');
$loader->register();

$r = new Worker1\Repositories\Worker1();

var_dump($r);

Here is the worker1 class:

<?php

namespace Worker1\Repositories;

// Worker1\Repositories and the class name is Worker1.

class Worker1 {
    public function __construct()
    {
        var_dump('I AM HERE!!', __DIR__, __FILE__, __LINE__);
    }
}

Here is the screen output:

string 'I AM HERE!!' (length=11)
string 'P:\developer\xampp\htdocs\testmysql\BackgroundWorkers\Worker1\Repositories' (length=74)
string 'P:\developer\xampp\htdocs\testmysql\BackgroundWorkers\Worker1\Repositories\Worker1.php' (length=86)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top