Articles

Laravel namespaces: what they are and how they work

I namespace in Laravel they are definited as an element class, where each element has a different name than its associated class. 

The keyword use allows us to shorten the namespace. Let's see this example:

namespace App\Models;
 
class File {

    public function TheMethodThatGetsFiles()
    {
    }
}

Namespaces are normally used in controllers

app/controllers/FileController.php

namespace App\Controllers;

use App\Models\File;

class FileController {
    public function someMethod()
    {
        $file = new File();
    }
}

When you put a class in a namespace, to access any of the built-in classes, you need to call them from Root Namespace

For example $stdClass = new stdClass(); becomes $stdClass = new \stdClass();

To import others namespace:

use App\Models\File;

This will allow you to use the class File without the prefix namespace.

Innovation newsletter
Don't miss the most important news on innovation. Sign up to receive them by email.

You have to put the namespace above to easily understand the file dependencies. After that, run the composer dump-autoload. If you want to log in to FileController, it will be necessary defideny route and specify the fully qualified namespace which will redirect it to the specified method of the controller.

Route::get('file', 'App\\Controllers\\FileController@TheMethod');

Declaration of namespace

The keyword use allows developers to shorten the namespace.

use <namespace-name>;

Il namespace predefinito used in Laravel is App, however a user can edit the namespace to match the web application. Creating a namespace deficreated by the user with the artisan command is as follows:

php artisan app:name SocialNet

Il namespace, once created, may include various features that can be used in controller and in various classes.

BlogInnovazione.it

You might also be interested in ...

Innovation newsletter
Don't miss the most important news on innovation. Sign up to receive them by email.

Latest Articles

Innovative intervention in Augmented Reality, with an Apple viewer at the Catania Polyclinic

An ophthalmoplasty operation using the Apple Vision Pro commercial viewer was performed at the Catania Polyclinic…

May 3, 2024

The Benefits of Coloring Pages for Children - a world of magic for all ages

Developing fine motor skills through coloring prepares children for more complex skills like writing. To color…

May 2, 2024

The Future is Here: How the Shipping Industry is Revolutionizing the Global Economy

The naval sector is a true global economic power, which has navigated towards a 150 billion market...

May 1, 2024

Publishers and OpenAI sign agreements to regulate the flow of information processed by Artificial Intelligence

Last Monday, the Financial Times announced a deal with OpenAI. FT licenses its world-class journalism…

April 30 2024