How to use namespace in a Class?

10

I'm using the AWS SDK for PHP from Amazon and for this I need the class S3Client .

I was seeing an example upload to amazon and did so:

require '../aws/aws-autoloader.php';

use Aws\S3\S3Client;

$s3 = S3Client::factory($config);

Now I wanted to include S3Client in my communication class with amazon ( ConnectionCloud ). The problem is that it gives the following error:

  

PHP Fatal error: Class 'S3Client' not found

How do I declare the class  'S3Client' inside my class ConnectionCloud ?

    
asked by anonymous 11.11.2014 / 13:37

1 answer

10

Your error is probably in the autoload implementation that is not finding the requested class in use .

Use Composer to manage your dependencies and classes when working with namespaces in PHP. Since it already includes an autoload that supports community standards, you will not have any major problems working with external libraries:

File index.php

<?php

// Autoload do Composer
require 'vendor/autoload.php';

// Instancio uma classe qualquer
$cloud = new MyApp\CloudProvider();

echo $cloud->getProviderClass();

Class CloudProvider.php

<?php namespace MyApp;

// Minha classe está acessando uma biblioteca externa, localizada na pasta vendor
use Aws\S3\S3Client;

class CloudProvider {

    protected $provider;

    public function __construct($config)
    {
        $this->provider = S3Client::factory($config);
    }

    public function getProviderClass()
    {
        return get_class($this->provider);
    }

}

composer.json : Composer configuration

{
    "require": {
        "aws/aws-sdk-php": "2.7.*"
    },
    "autoload": {
        "psr-4": { "MyApp\": "" }
    }
}

Example: link

Explanation

To make use of PHP namespaces automatically, without having to include files via require , we need to implement a autoload in PHP and follow a convention to name our classes and the folder structure. In this answer we have a simple implementation of autoload.

Note that even in a simple implementation, there is a pattern for naming classes. The PHP community adopts some standards with specific rules known as PSR-0 and PSR-4 ( more about PSR ) to name classes and folders.

So that we do not need to implement autoload in all of our projects manually, we can use a ready implementation. The most commonly used is Composer , which in addition to being compliant with the above standards, is also a dependency manager .

After installing Composer, just create a composer.json file and set it inside namespace of your application and the path of your files. It will create a vendor folder in your project, which will include the dependencies of your project and a autoload.php ready to use.

More information on how to install Composer and use it you can find here and also at documentation in .

    
14.11.2014 / 17:49