analogueorm / analogue

Analogue ORM : Data Mapper ORM for Laravel/PHP
MIT License
635 stars 52 forks source link

Can we map columns to class properties? #280

Closed odahcam closed 5 years ago

odahcam commented 5 years ago

Disclaimer: I'm using Eloquent and Analogue outside of Laravel on a Slim project.

I would like to know if it is possible to map columns to class properties, most because of type checking that Eloquent ridiculously can’t do in a no magical way.

adrorocker commented 5 years ago

Yes, you can use Plain PHP objects for that. Here is a simple example:

// MovieMap.php
namespace App\Maps;

use Analogue\ORM\EntityMap;

class MovieMap extends EntityMap
{
    protected $properties = [
        'id',
        'title',
    ];
}

// Movie.php

namespace App\Entity;

class Movie
{
    /**
     * @var int
     */
    protected $id;

    /**
     * @var string
     */
    protected $title;

    ... 
    // Getters and Setters and other business logic
}

// register entity normally
use App\Entity\Movie;
use App\Map\MovieMap;

$analogue->register(Movie::class, MovieMap::class); 
odahcam commented 5 years ago

That's way cleaner than Eloquent 😮 , thanks!

odahcam commented 5 years ago

What about properties with different names from DB columns?

adrorocker commented 5 years ago

I haven't test this scenario (plain PHP object and mapped DB columns), but I think It can work if you map DB columns to properties like this:


// MovieMap.php
namespace App\Maps;

use Analogue\ORM\EntityMap;

class MovieMap extends EntityMap
{
    protected $properties = [
        'ID',
        'Title_Of_Movie',
    ];

    protected $mappings = [
        'ID' => 'id',
        'Title_Of_Movie' => 'title',
    ];
}

// Movie.php

namespace App\Entity;

class Movie
{
    /**
     * @var int
     */
    protected $id;

    /**
     * @var string
     */
    protected $title;

    ... 
    // Getters and Setters and other business logic
}