0
votes

I am new to using composer and psr-0. I have tried a small app using composer and psr-0. I have used namespace to load a particular class. When i call a class using composer vendor/autoload I am getting class not found error.

My composer.json file:/var/www/html/silexapp/composer.json

{
"require": {
    "silex/silex": "~2.0",
    "symfony/console": "~2.6"
},
"autoload": {
    "psr-0": {
        "MyApp": "/silexapp/app"
    }
}
}

My composer vendor autoload file: /var/www/html/silexapp/vendor/autoload.php

     <?php

      // autoload.php @generated by Composer

     require_once __DIR__ . '/composer' . '/autoload_real.php';

    return ComposerAutoloaderInitf7241d907c173a8d77da0791cc918856::getLoader();

My class file name Underline.php: /var/www/html/silexapp/app/Tnq/Todo/Command/Underline.php

      <?php 
      namespace MyApp\Tnq\Todo\Command;
     class Underline{

        public function add($a,$b){

        return $result = $a+$b;

     }

   }

  ?>

My another class file name Bold.php: /var/www/html/silexapp/app/Tnq/Todo/Command/Bold.php

    <?php
    require_once "../../../../vendor/autoload.php";
    //require_once "Underline.php";

   use MyApp\Tnq\Todo\Command as tool;

   echo "this is the index file to check namespace.";
   $c = new tool\Underline();
   echo "=============================";
   echo "Addition : ".$c->add(2,2);
   ?>

I am getting "class not found error" in my bold.php class file, when I use autoload file. But when I directly included the underline class file, I am getting the output. Why it is not working when I use autoload?

Can anyone help me to find the issue?

1

1 Answers

1
votes

The "key" should be a directory under the path you put as "value", that should be relative to your working directory. To look at it in a simple way, the namespace should map the directory structure; you are missing a MyApp directory.

If in your composer.json have:

    "autoload": {
        "psr-0": {
            "MyApp\\": "app/"
        }
    }

Then you need a MyApp directory under app/. Try this:

composer.json:

// /var/www/html/silexapp/composer.json
{
    "require": {
        "silex/silex": "~2.0",
        "symfony/console": "~2.6"
    },
    "autoload": {
        "psr-0": {
            "Tnq\\": "app/"
        }
    }
}

Underline.php:

<?php
// /var/www/html/silexapp/app/Tnq/Todo/Command/Underline.php 
namespace Tnq\Todo\Command;

class Underline
{
    public function add($a,$b)
    {
        return $result = $a+$b;
    }
}

Bold.php:

<?php
// /var/www/html/silexapp/app/Tnq/Todo/Command/Bold.php
require_once "../../../../vendor/autoload.php";

use Tnq\Todo\Command as tool;

echo 'this is the index file to check namespace.' . PHP_EOL;
$c = new tool\Underline();
echo "=============================";
echo "Addition : ".$c->add(2,2);

In theory, that should works (not tested :) )


sources: