PHP code example of thruster / data-mapper

1. Go to this page and download the library: Download thruster/data-mapper library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

thruster / data-mapper example snippets


class SimpleMapper extends BaseDataMapper {
    /**
     * @param Request $input
     */
    public function map($input)
    {
        return [
            'id' => $input->getId(),
            'name' => $input->getName()
        ];
    }
}

$dataMappers = new DataMappers();
$dataMappers->addMapper(new SimpleMapper());
$dataMappers->getMapper(SimpleMapper::class)->map($input);

class ItemMapper extends BaseDataMapper {
    /**
     * @param Request $input
     */
    public function map($input)
    {
        return [
            'id' => $input->getId(),
            'name' => $input->getName()
        ];
    }
}

class MainMapper extends BaseDataMapper {
    /**
     * @param Request $input
     */
    public function map($input)
    {
        return [
            'id' => $input->getId(),
            'name' => $input->getName(),
            'items' => $this->getMapper(ItemMapper::class)->mapCollection($input->getItems())
        ];
    }
}

$dataMappers = new DataMappers();
$dataMappers->addMapper(new MainMapper());
$dataMappers->addMapper(new ItemMapper());
$dataMappers->getMapper(MainMapper::class)->map($input);

class UserRegistrationMapper extends BaseDataMapper implements ValidateableDataMapperInterface {
    /**
     * @param Request $input
     */
    public function map($input)
    {
        $user = new User();
        
        $user->setUsername($input->get('username'));
        $user->setPassword($input->get('password'));
    }

    public function supports($input) : bool
    {
        return ($input instanceof Request);
    }
    
    public function getValidationGroups($input) : array
    {
        return ['full'];
    }
}

$dataMappers = new DataMappers();
$dataMappers->setValidator(Validation::createValidator());

$dataMappers->addMapper(new UserRegistrationMapper());
$dataMappers->getMapper(UserRegistrationMapper::class)->map($input);

$simpleMapper = new DataMapper(
    new class extends BaseDataMapper {
        /**
         * @param Request $input
         */
        public function map($input)
        {
            return [
                'id' => $input->getId(),
                'name' => $input->getName()
            ];
        }
    
        public function supports($input) : bool
        {
            return true;
        }
    }
);

$simpleMapper->map($input);