0

I have trouble adding my own namespaces to composer with PSR-0. I have read this and this but I still can't make it work

composer.json

{
"require": {
    "klein/klein": "2.0.x",
    "doctrine/orm": "2.4.4"

},
"autoload": {
    "psr-0": {
        "mynamespace":        "src/"
        }
}
}

The src folder is placed inside the same directory as composer.json

The src directory has the following structure

src
└── mynamespace
    ├── Keys.php

Keys.php

<?php
namespace mynamespace\Keys;

define ("API_KEY", "XXXXXXXXXXXX");
?>

index.php

use Klein\Klein;
use mynamespace\Keys;
require_once __DIR__ . '/vendor/autoload.php';

$klein = new Klein(); // works
echo API_KEY;  // Undefined constant
2
  • PSR-x autoloaders only "understand" single-namespace single-class include scripts. Even if they did provide full language support, PHPs current spl_autoload() does not recognize constant or plain function lookups. The echo API_KEY does not trigger anything, neither does the use ..\Keys declaration. Commented Aug 31, 2014 at 19:14
  • @mario so I have to use require to load my own namespaces? Commented Aug 31, 2014 at 19:48

1 Answer 1

1

You can only load classes, interfaces and traits with autoloading.

Because all you do is add a use clause which does not do anything by itself with autoloading (i.e. it does not load something), and you do not use a class, nothing happens.

I recommend using class constants. They may be put into classes or interfaces:

namespace mynamespace;

interface Keys {
    const API_KEY = 'XXXXXXXX';
}

use mynamespace/Keys;
echo Keys::API_KEY;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.