Search code examples
phpzend-frameworkdoctrine-ormentityzend-framework3

How to autoload inherited doctrine entity in Zend Framework 3?


<?php
namespace MyProject\Model;

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"person" = "Person", "employee" = "Employee"})
 */
class Person
{
    // ...
}

/**
 * @Entity
 */
class Employee extends Person
{
    // ...
}

How to define Autoload for above doctrine entity inheritance ? Or can we put each entity in separate file such as Entity\Person.php , Employee\Person.php ?


Solution

  • You should put every PHP class in its own file, if you want your project to be compatible with (for example) PSR-4 (Autoloader).

    Citing from the PSR-4 specification:

    1. When loading a file that corresponds to a fully qualified class name …

      1. A contiguous series of one or more leading namespace and sub-namespace names, not including the leading namespace separator, in the fully qualified class name (a “namespace prefix”) corresponds to at least one “base directory”.
      2. The contiguous sub-namespace names after the “namespace prefix” correspond to a subdirectory within a “base directory”, in which the namespace separators represent directory separators. The subdirectory name MUST match the case of the sub-namespace names.
      3. The terminating class name corresponds to a file name ending in .php. The file name MUST match the case of the terminating class name.

    So, if you create a class Person in MyProject\Model namespace, the autoloader will find it only in a …/Model/Person.php file. And an Employee class must go to a separate …/Model/Employee.php file in order to be available to the autoloader.