Reputation: 1626
I am using Alchemy API for filter out some data. Everything works fine in the native code. But when i used it in my Laravel Controller it throws Cannot redeclare class. My controller,alchemyapi.php and example.php
are in the same directory. Here is how i include alchemyapi.php
in native code
<?php
require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI("MY API KEY"); ?>
But when i include it in the controller it throws my the error. is there something i am missing ?
require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI("MY API KEY");
The native code(example.php
) works well without any issue. But in laravel controller it throws a error saying Cannot redeclare class AlchemyAPI
in alchemyapi.php line 20
Upvotes: 1
Views: 1840
Reputation: 1839
Instead of using require_once
use namespace
in your alchemyapi.php
and then use use
for same namespace
in your MyController
alchemyapi.php
<?php
namespace App\Http\Controller;
class AlchemyApi {
//your code
}
MyController.php
<?php
namespace App\Http\Controller;
use App\Http\Controller\AlchemyApi;
class MyController {
$alchemy = new AlchemyApi("Your_api_key");
}
Upvotes: 2
Reputation: 1974
OK, so what I think is happening is that alchemyapi.php
is somehow already being included by the composer autoloader.
Try this.
lib
in the root of your project.Under the "autoload" section in your composer.json
add the following code. Make sure the JSON is valid:
"files": [
"lib/alchemyapi.php",
],
Run composer dump-autoload
. If it errors, your composer.json
is invalid or you haven't put the file in the correct place.
Delete require_once 'alchemyapi.php';
from your controller.
When dealing with composer, this is how you deal with classes in the global namespace. After running composer it scan those directories in app
for PSR-4 classes.
I can't be sure but I think that composer is looking for it and you are also manually requiring it. That would explain why PHP thinks you are redeclaring the class.
Upvotes: 0