troytft/data-mapper-bundle

Allow mapping data to models

Installs: 17 164

Dependents: 0

Suggesters: 0

Security: 0

Stars: 8

Watchers: 3

Forks: 3

Type:symfony-bundle

v3.1.0 2022-08-25 09:40 UTC

README

[DEPRECATED] Project is closed, for new applications should use https://github.com/troytft/rest-api-bundle

Installation

Install using Composer:

composer require troytft/data-mapper-bundle

Add the bundle to your AppKernel.php:

$bundles = array(
    // ...
    new Troytft\DataMapperBundle\DataMapperBundle(),
);

Usage

Model:

<?php
namespace Common\Model;

use Common\Constraint as AppAssert;
use Symfony\Component\Validator\Constraints as Assert;
use Troytft\DataMapperBundle\Annotation\DataMapper;

class PostsFilter
{
    /**
     * @DataMapper(type="string")
     */
    protected $query;

    /**
     * @DataMapper(type="entity", options={"class": "CommonBundle:City"})
     * @Assert\NotBlank
     */
    protected $city;

    /**
     * @return mixed
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * @param mixed $value
     */
    public function setCity($value)
    {
        $this->city = $value;

        return $this;
    }

    /**
     * @return string
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * @param string $value
     */
    public function setQuery($value)
    {
        $this->query = $value;
        
        return $this;
    }
}

Controller:

    public function handleRequest($model, $clearMissing = true, $groups = ['Default'], $validationGroups = ['Default'])
    {
        /** @var Request $request */
        $request = $this->get('request');
        $data = $request->getRealMethod() == 'GET' ? $request->query->all() : $request->request->all();

        /** @var DataMapperManager $manager */
        $manager = $this->get('data_mapper.manager');

        return $manager
            ->setGroups($groups)
            ->setValidationGroups($validationGroups)
            ->setIsClearMissing($clearMissing)
            ->handle($model, $data);
    }