Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing Own Classes with Composer

I'm new to composer and autoloaders. I think I also lack of file organization strategies. I'm trying to build up a new project on slimframework. I have some classes for Slim. But I can not autoload them in my project.

/

  • composer.json
  • composer.phar
  • vendor
  • config
    • someapiparams.php
    • database.php
    • cache.php
    • general.php
  • public
    • index.php
  • models
  • libraries
    • Foo
    • Slim
      • Config.php
      • Cache.php

/composer.json:

"autoload": {
    "psr-0": {
        "Foo": "libraries/"
    }
}

/libraries/Foo/Slim/Config.php:

<?php
class Config {
    /**
    * Loads a file based on $key param under ROOT . "/config",
    * if not already loaded. 
    * Then returns an array.
    */
    public static function get($key) {}

}

/libraries/Foo/Slim/Cache.php:

<?php
class Cache{
    /**
    * Initialize a caching engine defined in config file if not already done.
    * Then runs corrensponding engine methods for getting and setting.
    */
    public static function init() {
       $config = Config::get("cache");
       // initialize driver.
    }
    public static function __get($key) {}
    public static function __set($key, $value, $params) {}

}

/public/index.php:

require ROOT."/vendor/autoload.php";
$app = new Slim\Slim();
var_dump(Config::get("database")); exit;
//var_dump(Foo\Slim\Config::get("database")); exit;
//var_dump(Slim\Config::get("database")); exit;

Error is Config class not found.

like image 744
hctopcu Avatar asked Nov 01 '22 05:11

hctopcu


1 Answers

You have forgotten to put:

namespace Foo/Slim;

at the top of /libraries/Foo/Slim/Cache.php (or have possibly have snipped it for the code example).

If adding the namespace doesn't fix it, you should step through the code with a debugger, and see exactly what files the Composer autoloader is searching for, when it tries to load the class and fails.

like image 165
Danack Avatar answered Nov 17 '22 12:11

Danack