PhpStorm 2024.1 Help

Configure PHP namespaces in a project

PhpStorm supports the PSR-0/PSR-4 autoloading standard, which stipulates that namespace names in PHP should be mapped to the directory structure. The directory marked with the Source root type in PhpStorm is considered to be the root for namespaces, and every directory created under it is considered to be a separate namespace.

When the Source root type is set, PhpStorm autocompletes the namespace name when you create a new class/interface/etc. inside this directory. For namespace names that don't match the PSR-0/PSR-4 project structure, the IDE displays an inspection warning in the editor.

Detect namespace roots automatically

If you use Composer to manage PSR-0/PSR-4 autoloading, PhpStorm marks the directories as Source automatically based on the contents of the composer.json file when you open the project.

If a project does not have a composer.json file with the "autoload" section in it, PhpStorm detects at least one file with a namespace and prompts you to set the namespace root by showing a notification message. If no namespace root has been configured yet, PhpStorm prompts you to configure the namespace root when you create a new class.

You can also trigger automatic detection of namespace roots by choosing Code | Detect PSR-0 Namespace Roots from the main menu. The Directories dialog that opens, shows the folders under the project root folder with the project root folder marked as Source, which means that it is the root for all the namespaces in it. Accept the settings by clicking OK, or configure the namespace root manually.

Configure namespace roots manually

  1. In the Settings dialog (Ctrl+Alt+S) , go to Directories.

  2. The right-hand pane of the Directories page that opens shows all the content roots configured in the project. As a rule, there is one content root which is the root folder of the current project.

    The central pane shows all the folders under the selected content root. Select the folder to be treated as the namespace root and click Sources.

    It is perfectly fine to configure multiple source roots: PhpStorm will treat each of those as a namespace root and provide namespace hints for files underneath them. For example, every subfolder of a vendor folder can be marked as a namespace root. In the example below, we have two namespace roots: one for the actual application and one for a vendor folder:

    Configure namespace roots
  3. To configure a namespace prefix according to PSR-4, click the Edit properties button next to the relevant source folder (namespace root), and specify prefix to use in the Edit Root Properties dialog. To have the prefix applied to the automatically generated code too, select the For generated sources checkbox.

    Rename namespace root
Last modified: 11 February 2024