PhpStorm 2017.1 Help

Configuring PHP Namespaces in a Project

In this section:


PhpStorm comes with a configurable convention which specifies that the project root folder is also the root for the packages and namespaces. In other words: the project root folder is by default marked as Source and every directory created under it is considered a separate namespace. This complies with the PSR-0, also known as the Autoloading Standard, which prescribes that classes and namespaces in PHP should match the directory and file structure, and vice-versa.

According to PSR-4, any directory can be explicitly assigned a namespace prefix. With this project structure, autoloaders in different PHP frameworks become interoperable.

Detecting namespace roots automatically

When you open a project that contains at least one file with a namespace, PhpStorm displays a message with a proposition to set the namespace root.

Accordingly, when no namespace root has been configured yet and you create a class, PhpStorm proposes to configure the namespace root.

You can also trigger namespace root detection by choosing Code | Detect PSR-0 Namespace Roots on the main menu. The Directories dialog box 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 as described below. Learn more about marking folders in Configuring Folders Within a Content Root.

Configuring namespace roots manually

  1. Open the Settings / Preferences Dialog by pressing Ctrl+Alt+S or by choosing File | Settings for Windows and Linux or PhpStorm | Preferences for macOS, and click Directories under Project:<Project Name>.
  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:


  3. To configure a namespace prefix according to PSR-4, click ps_configure_namespace_prefix_icon.png next to the relevant source folder (namespace root), and specify prefix to use in the Edit Root Properties Dialog box. To have the prefix applied to the automatically generated code too, select the For generated sources check box.

See Also

Last modified: 19 July 2017