spotorm / spot2

Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer
http://phpdatamapper.com
BSD 3-Clause "New" or "Revised" License
601 stars 101 forks source link

First Installation for all entities #232

Open koraykupe opened 7 years ago

koraykupe commented 7 years ago

Hi,

What is best practice to create all entities by not defining all of them one by one?

I use

$spot->mapper('Entity\Post')->migrate();

command for each entity. Is there a better way?

Thank you.

willemwollebrants commented 7 years ago

Fwiw: I use the following function:

/**
 * @param string $dir
 * @param string $namespace
 * @param \Spot\Locator $locator
 */
function migrateEntities(string $dir, string $namespace, \Spot\Locator $locator)
{
    $contents = array_filter(scandir($dir), function ($entry) {
        return !in_array($entry, ['.', '..']);
    });

    foreach ($contents as $entry) {
        if (is_file($dir . DIRECTORY_SEPARATOR . $entry)) {
            $classname = $namespace . substr($entry, 0, -4);
            //check if the class exists and is an Entity
            if (class_exists($classname) && is_subclass_of($classname, \Spot\Entity::class)) {
                $locator->mapper($classname)->migrate();
            }
        } else {
            //must be a subdirectory, so scan that too
            migrateEntities(
                $dir . DIRECTORY_SEPARATOR . $entry,
                $namespace . "{$entry}\\",
                $locator
            );
        }
    }
}

It has 3 parameters: the directory where your entities are stored, the namespace (with trailing ) and the Spot\Locator object. It will scan through all files and directories and if it finds a valid entity it will run the migration.