Problem with use in PHP

Asked

Viewed 86 times

2

I am developing an application that sends an image to a Bucket on Amazon and I am using the sdk pure

To send use the following code:

function especifica(){
    require '..\..\lib\aws\aws-autoloader.php';
    use Aws\S3\S3Client;

    define("ACCESS_KEY_AMAZON", "");
    define("SECRET_KEY_AMAZON", "");

    try {
        $clientS3 = S3Client::factory(array(
            'region'   => 'região',
            'version' => 'latest',
            'key'    => ACCESS_KEY_AMAZON,
            'secret' => SECRET_KEY_AMAZON
        ));
        $response = $clientS3->putObject(array(
            'Bucket' => "bucket",
            'Key'    => "profile_picture/".$_POST['idusuario'].".png",
            'SourceFile' => $_POST['hidden_cropped'],
        ));

        die(var_dump($response));
        echo "Objeto postado com sucesso, endereco <a href='{$response['ObjectURL']}'>{$response['ObjectURL']}</a>";
    } catch(Exception $e) {
        log_errors( "Edit picture, upload to amazon S3".PHP_EOL."Exception: ".$e);
    }
}

Turns out my API has more than one function in the same file, type change photo, change basic information, unsubscribe, change password and so on.

That’s why I chose to keep the require to be executed only inside the photo change function, but was directly receiving the error:

Unexpected 'use' error (T_USE)

After researching about I discovered that the namespace use can only be declared no escopo mais externo de um arquivo.

Source: Unexpected 'use' (T_USE) error when using autoload

Okay, I put the use in the outermost scope, more or less so:

require '..\..\lib\aws\aws-autoloader.php';
use Aws\S3\S3Client;

function especifica(){    
    define("ACCESS_KEY_AMAZON", "");
    define("SECRET_KEY_AMAZON", "");

    try {
        $clientS3 = S3Client::factory(array(
            'region'   => 'região',
            'version' => 'latest',
            'key'    => ACCESS_KEY_AMAZON,
            'secret' => SECRET_KEY_AMAZON
        ));
        $response = $clientS3->putObject(array(
            'Bucket' => "bucket",
            'Key'    => "profile_picture/".$_POST['idusuario'].".png",
            'SourceFile' => $_POST['hidden_cropped'],
        ));

        die(var_dump($response));
        echo "Objeto postado com sucesso, endereco <a href='{$response['ObjectURL']}'>{$response['ObjectURL']}</a>";
    } catch(Exception $e) {
        log_errors( "Edit picture, upload to amazon S3".PHP_EOL."Exception: ".$e);
    }
}

And it worked, only I wanted to know if it affects my other functions? In charging time mainly, since the Amazon sdk has 6MB.

  • Which version of php vc uses?

  • PHP Version 7.0.14-1 Running on an Ubuntu server

2 answers

3

I am considering that you are dealing with a legacy application and that it is not convenient to adopt the best loading practices so I see that you can leave the way it is without compromising performance but can also remove the line from the use and use the fully qualified name of the object, placing the backslash at the beginning, example:

<?php
    require_once '..\..\lib\aws\aws-autoloader.php';
    $clientS3 = \Aws\S3\S3Client::factory( //...
  • but how to use the use, Does it affect performance? I mean, it loads the whole class of aws sdk, for all functions, even if they do not use it?

  • I guess you don’t have to worry about it because the optimization is done in the language core

3


The operator use serves as an alias for namespaces. There is another purpose of use in which you pass an argument by reference, but it is not the case here so the focus will only refer to what you asked:

And it worked, only I wanted to know if it affects my other duties? In charging time mainly, since the sdk from Amazon has 6MB.

The operator use creates only a "shortcut" (alias). Does not load the alias target object. Therefore, no need to worry about memory cost, etc. It is obvious that there is a cost related to the use of the operator, however the objects are not loaded automatically.

What may go wrong in your application is, if the application does not have a good organization, there may be some name conflict, but it is something unusual and will only happen if you write the application in a very disorganized way, declaring commonly used naming functions, classes or namespaces, increasing the chances of conflict with third party systems/libraries that you are importing into your project (include, require)

This is one of the purposes of using the namespace. Avoid this problem of conflicting functions with equal names.

An important detail in your case is that you are applying the alias to the global scope. That is, you can invoke the classes that are under the namespace Aws\S3\S3Client without having to specify the namespace.

Example, in a snippet of code invokes S3Client::factory(). This is only possible because the alias Aws\S3\S3Client has been applied to the basis of the overall scope. If you need to invoke a function or class outside that namespace, you need to specify the full or relative path with the appropriate indents.

Particularly I prefer to specify an alias instead of playing for root:

use Aws\S3\S3Client as AWS;

So just invoke it like this: AWS\S3Client::factory(). But this depends a lot on the project. If the project does not use any other namespace, you can play the root alias as you are doing. Sure, as long as you’re aware about name conflicts.

To avoid such worries, just create a pattern for your projects, always organizing them in a namespace of their own.




Obs: I suggest you edit the title and the question for something more appropriate.
To better understand how to ask questions: Manual on how NOT to ask questions

Browser other questions tagged

You are not signed in. Login or sign up in order to post.