I'm currently building an application that will require a few different name spaces, however most of the application I want to put under the app namespace.
In my index.php file I declared to use the app namespace, however PHP still insists my class cannot be found like so...
<?php
define('PATH',strtok ( $_SERVER['REQUEST_URI'] , '?' ));
define("ROOT",$_SERVER['DOCUMENT_ROOT'].'/',true);
require 'vendor/autoload.php';
require 'app/class_loader.php';
use Carbon\Carbon;
use app\routing;
$routing = new routing;
$routing->router();
and inside my routing class I declare it as part of the app namespace like this
<?php
namespace app;
class routing
{
However I keep getting Fatal error: Class 'app\routing' not found in /var/www/my_app/index.php on line 15
This is my autoload file
<?php
function autoload_class_multiple_directory($class_name)
{
# List all the class directories in the array.
$array_paths = array(
'app/controllers',
'app/models',
'app/services',
);
foreach($array_paths as $path)
{
$file = $path.'/'.$class_name.'.php';
if(is_file($file))
{
include $file;
}
}
}
spl_autoload_register('autoload_class_multiple_directory');
I thought this is how namespaces worked? I want to ensure I make my application as easy to follow and code in from the get-go, could somebody please help point me in the right direction?
cheers!
Related
I'm having some hard time wrapping around namespaces in PHP, especially when you code needs to interact with scripts residing in another namespace. I downloaded a Shopify API toolkit and trying to get it working. Everything was fine before I started adding namespaces to my code (which is required or threre is script collisition with other Wordpress plugins on my site). Also, the weird namespace {} bit at the top is because in this same file I want a globally accessible function for making the class a singleton.
Looking forward to learning more about how this works.
#### FILE BEING CALLED
namespace {
function SomeFunctionToBeAccessedGlobally() {
return 'Hello';
}
}
namespace MySpecialApp {
class ShopifyImport {
public function __construct() {
// Do Whatever
$this->doImport();
}
public function doImport() {
require __DIR__ . '/vendor/autoload.php';
$credential = new Shopify\PrivateAppCredential('standard_api_key', 'secret_api_key', 'shared_api_key');
$client = new Shopify\Client($credential, 'shop_url', [ 'metaCacheDir' => './tmp' ]);
}
}
}
#### FILE '/vendor/autoload.php'
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit73503f8de5d68cdd40a9c0dfd8a25b44::getLoader();
I do noice that some of the files which where part of the repository cloned into vendor have namespace Slince\Shopify; declarations. I tried to do a use with that namespace within my original namespace but it also didn't work.
The PHP Error being reported is:
Fatal error: Uncaught Error: Class
'MySpecialApp\Shopify\PrivateAppCredential' not found in
/.../ShopifyImporter.php:139 Stack trace: #0 (Blah Blah Blah)
Your code tries to create a new Shopify\PrivateAppCredential() object in the current namespace. However, this class does not exist in your namespace since it is part of the "vendor" namespace.
You can "reset" (read fallback) to the global namespace for your object creations by adding a \ in front of them, as described in the documentation:
$credential = new \Shopify\PrivateAppCredential('standard_api_key', 'secret_api_key', 'shared_api_key');
You can check the difference here without \ and with \.
I am using Symfony 2.4
I have a PHP file OAuth.php which has multiple classes inside that.
Code of OAuth.php is as below
<?php
namespace RT\AuthBundle\DependencyInjection\Vzaar;
use Exception;
class OAuthException extends Exception {
// pass
}
class OAuthConsumer {
//some code
}
class OAuthToken {
//some code
}
?>
I am inheriting above file in Vzaar.php file which is with in same namespace and it's code is as below
<?php
namespace RT\AuthBundle\DependencyInjection\Vzaar;
/*require_once 'OAuth.php';
require_once 'HttpRequest.php';
require_once 'AccountType.php';
require_once 'User.php';
require_once 'VideoDetails.php';
require_once 'VideoList.php';
require_once 'UploadSignature.php';*/
use RT\AuthBundle\DependencyInjection\Vzaar\OAuth;
use RT\AuthBundle\DependencyInjection\Vzaar\HttpRequest;
use RT\AuthBundle\DependencyInjection\Vzaar\AccountType;
use RT\AuthBundle\DependencyInjection\Vzaar\User;
use RT\AuthBundle\DependencyInjection\Vzaar\VideoDetails;
use RT\AuthBundle\DependencyInjection\Vzaar\VideoList;
use RT\AuthBundle\DependencyInjection\Vzaar\UploadSignature;
//use RT\AuthBundle\DependencyInjection\Vzaar\OAuth\OAuthConsumer;
Class Profile
{
public static function setAuth($_url, $_method = 'GET')
{
$consumer = new OAuthConsumer('', '');
//some code
}
}
?>
Creating new object of OAuthConsumer class throws error that
Fatal error: Class 'RT\AuthBundle\DependencyInjection\Vzaar\OAuthConsumer' not found in /var/temp/rt-web/src/RT/AuthBundle/DependencyInjection/Vzaar/Vzaar.php
1/1 ClassNotFoundException: Attempted to load class "OAuthConsumer" from namespace "RT\AuthBundle\DependencyInjection\Vzaar" in /var/temp/rt-web/src/RT/AuthBundle/DependencyInjection/Vzaar/Vzaar.php line 378. Do you need to "use" it from another namespace?
Because since 2.1 Symfony uses composer, and composer uses PSR-0/PSR-4 to autoloading the classes, you have to follow the namespace convention, so you have to create those classes in separate files and in the right directory structure, what is represented in the namespace.
EDIT
As Cerad mentioned in the comment, you can specify a class map in composer, although what is considered as a best practice with symfony projects, create every class in a separate file.
I am developing with php 5.5, I provided code of my file here
<?php
require_once 'jsonrpcphp/includes/jsonRPCClient.php';
class Client
{
private $remoteMain;
public function __construct($param)
{
$this->remoteMain = new jsonRPCClient('http://
urlTofile/nameOfFile.php');
This codes works absolutely fine but the issue comes when I need to put a namespace for the file as soon as I put a namespace at the top of the file, for example:
<?php
namespace packagename\subPackage;
require_once 'jsonrpcphp/includes/jsonRPCClient.php';
class Client
This error will be displayed
Class 'packagename\subPackage\jsonRPCClient' not found in
The question is this:
how to access a class which is not in my namespace and provided from 3rd parties when I need to have namespaces
thanks in advance
If you're in namespace packagename\subPackage, then new jsonRPCClient refers to the class packagename\subPackage\jsonRPCClient. If you want to use a class from the global namespace, you need to explicitly specify that:
new \jsonRPCClient
Alternatively, explicitly alias the class at the top of the file:
use jsonRPCClient;
new jsonRPCClient(...)
Please RTM: http://php.net/manual/en/language.namespaces.basics.php
I am working with a folder structure as follows:
classes
-common.php
-core.php
modules
-index/index.php
I am trying to use the common.php in my index.php file and I am facing error:
Fatal error: Class 'classes\Common' not found in
D:\xampp\htdocs\devmyproject\modules\index\index.php on line 7
My Code:
commom.php class:
**Directory:/root/classes/common.php**
<?php
namespace classes;
class Common
{
function __construct()
{
}
}
My index.php file which try to use the classes/commom.php
**Directory:/root/modules/index/index.php**
<?php
namespace modules\beneficiary;
use \classes as hp;
include_once 'config.php';
$common = new \classes\Common();
//To Get Page Labels
$labels = $common->getPageLabels('1');
I am includeing common.php in config.php
$iterator = new DirectoryIterator($classes);
foreach ($iterator as $file) {
if ($file->isFile())
include_once 'classes/' . $file;
}
My Try:
It works fine when I use the folder structure as follows:
classes
-common.php
-core.php
modules
-index.php
If I use another folder inside modules it get error? I am not sure about he hierarchy of folders when using namespace can some one help me?
You have to either include common.php in index.php (better: use one of its relatives include_once or require_once) or set up an autoloader using spl_autoload_register() (or, not recommended, writing an __autoload() function).
I have a folder in my library folder which is named after my website. The folder path is like:
~\www\library\myWebsite.com
If I'm using Zend autoloader to load the namespace of everything in the library path, will I have any trouble autoloading a class from that file with a namespace like this:
\myWebsite.com\myClass::myFunction();
I have looked online for documentation on this and I can't find any info about using periods in this way.
I tried it and the complication is in PHP. I think Zend is registering the namespace fine, because when I call \Zend_Load_Autoloader::getRegisteredNamespaces() it shows that it's registered. but when I call the static method from the fully qualified namespace, php gives an error of this:
Fatal error: Undefined constant 'myWebsite' in /home/jesse/www/application/controllers/MyController.php on line 15
It seems like PHP is terminating the namespace identifier, during parsing, at the . (period character). This is dissapointing because to me having a library named after the website was important to my design.
I will rename the directory to myWebsitecom or possibly make the .com it's own sub directory like
myWebsite\com and incorporate that into my namespace tree like: \MyNamespace\Com\MyClass::myFunction();
The easiest way to find out is to try it.
If it doesn't work, you could always write a custom autoloader to make it work. I don't have much experience with php namespaces, but the autoloader would look something like this (I imagine you'll have to tinker with it a bit to determine the correct file path given the class name):
<?php
class My_Loader_Autoloader_MyWebsite implements Zend_Loader_Autoloader_Interface {
/**
* (non-PHPdoc)
* #see Zend_Loader_Autoloader_Interface::autoload()
*/
public function autoload($class) {
if (strtolower(substr($class, 0, 9)) == 'mywebsite') {
$file = realpath(APPLICATION_PATH . '/../library/myWebsite.com/' . $class);
if ($file) {
require_once $file;
return $class;
}
}
return false;
}
}
then put this in your bootstrap:
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->pushAutoloader(new My_Loader_Autoloader_MyWebsite());
and if this class must be in that myWebsite.com directory, you could just cheat and throw in a require in there too:
require_once(APPLICATION_PATH . '/../library/myWebsite.com/Loader/Autoloader/MyWebsite.php');