{"id":15732693,"url":"https://github.com/nilportugues/laravel5-json","last_synced_at":"2025-03-13T05:31:13.466Z","repository":{"id":57027212,"uuid":"40885497","full_name":"nilportugues/laravel5-json","owner":"nilportugues","description":"Laravel 5 JSON Transformer Package","archived":false,"fork":false,"pushed_at":"2016-03-06T10:14:29.000Z","size":35,"stargazers_count":3,"open_issues_count":1,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-26T18:57:02.895Z","etag":null,"topics":["api","json","json-api","laravel","laravel5","lumen","marshaller","php","php7","serialization","serializer","transformer"],"latest_commit_sha":null,"homepage":"http://nilportugues.com","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nilportugues.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-08-17T10:26:59.000Z","updated_at":"2022-02-12T14:01:41.000Z","dependencies_parsed_at":"2022-08-23T16:30:08.762Z","dependency_job_id":null,"html_url":"https://github.com/nilportugues/laravel5-json","commit_stats":null,"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Flaravel5-json","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Flaravel5-json/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Flaravel5-json/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Flaravel5-json/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nilportugues","download_url":"https://codeload.github.com/nilportugues/laravel5-json/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243351173,"owners_count":20276894,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","json","json-api","laravel","laravel5","lumen","marshaller","php","php7","serialization","serializer","transformer"],"created_at":"2024-10-04T00:21:42.358Z","updated_at":"2025-03-13T05:31:12.907Z","avatar_url":"https://github.com/nilportugues.png","language":"PHP","funding_links":["https://paypal.me/nilportugues"],"categories":[],"sub_categories":[],"readme":"# Laravel 5 JSON Transformer Package\n\n\n[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/nilportugues/laravel5-json-transformer/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/nilportugues/laravel5-json-transformer/?branch=master) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/a3933b7b-13ec-44cf-aef9-0dce25e44ef5/mini.png)](https://insight.sensiolabs.com/projects/a3933b7b-13ec-44cf-aef9-0dce25e44ef5) \n[![Latest Stable Version](https://poser.pugx.org/nilportugues/laravel5-json/v/stable)](https://packagist.org/packages/nilportugues/laravel5-json) \n[![Total Downloads](https://poser.pugx.org/nilportugues/laravel5-json/downloads)](https://packagist.org/packages/nilportugues/laravel5-json) \n[![License](https://poser.pugx.org/nilportugues/laravel5-json/license?)](https://packagist.org/packages/nilportugues/laravel5-json) \n[![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://paypal.me/nilportugues)\n\n*Compatible with Laravel 5.0, 5.1 \u0026 5.2*\n\n## Installation\n\nUse [Composer](https://getcomposer.org) to install the package:\n\n```\n$ composer require nilportugues/laravel5-json\n```\n\n\n## Laravel 5 / Lumen Configuration\n\n**Step 1: Add the Service Provider**\n\n**Laravel**\n\nOpen up `config/app.php` and add the following line under `providers` array:\n\n```php\n'providers' =\u003e [\n\n    //...\n    \\NilPortugues\\Laravel5\\Json\\Laravel5JsonServiceProvider::class,\n],\n```\n\n**Lumen**\n\nOpen up `bootstrap/app.php`and add the following lines before the `return $app;` statement:\n\n```php\n$app-\u003eregister(\\NilPortugues\\Laravel5\\Json\\Laravel5JsonServiceProvider::class);\n$app-\u003econfigure('json');\n```\n\nAlso, enable Facades by uncommenting:\n\n```php\n$app-\u003ewithFacades();\n```\n\n**Step 2: Add the mapping**\n\nCreate a `json.php` file in `config/` directory. This file should return an array returning all the class mappings.\n\n\n**Step 3: Usage**\n\nFor instance, lets say the following object has been fetched from a Repository , lets say `PostRepository` - this being implemented in Eloquent or whatever your flavour is:\n\n```php\nuse Acme\\Domain\\Dummy\\Post;\nuse Acme\\Domain\\Dummy\\ValueObject\\PostId;\nuse Acme\\Domain\\Dummy\\User;\nuse Acme\\Domain\\Dummy\\ValueObject\\UserId;\nuse Acme\\Domain\\Dummy\\Comment;\nuse Acme\\Domain\\Dummy\\ValueObject\\CommentId;\n\n//$postId = 9;\n//PostRepository::findById($postId); \n\n$post = new Post(\n  new PostId(9),\n  'Hello World',\n  'Your first post',\n  new User(\n      new UserId(1),\n      'Post Author'\n  ),\n  [\n      new Comment(\n          new CommentId(1000),\n          'Have no fear, sers, your king is safe.',\n          new User(new UserId(2), 'Barristan Selmy'),\n          [\n              'created_at' =\u003e (new \\DateTime('2015/07/18 12:13:00'))-\u003eformat('c'),\n              'accepted_at' =\u003e (new \\DateTime('2015/07/19 00:00:00'))-\u003eformat('c'),\n          ]\n      ),\n  ]\n);\n```\n\nAnd a series of mappings, placed in `config/json.php`, that require to use *named routes* so we can use the `route()` helper function:\n\n```php\n\u003c?php\n//config/json.php\nreturn [\n    [\n        'class' =\u003e 'Acme\\Domain\\Dummy\\Post',\n        'alias' =\u003e 'Message',\n        'aliased_properties' =\u003e [\n            'author' =\u003e 'author',\n            'title' =\u003e 'headline',\n            'content' =\u003e 'body',\n        ],\n        'hide_properties' =\u003e [\n\n        ],\n        'id_properties' =\u003e [\n            'postId',\n        ],\n        'urls' =\u003e [\n            'self' =\u003e ['name' =\u003e get_post'], //named route\n            'comments' =\u003e ['name' =\u003e 'get_post_comments'], //named route\n        ],\n    ],\n    [\n        'class' =\u003e 'Acme\\Domain\\Dummy\\ValueObject\\PostId',\n        'alias' =\u003e '',\n        'aliased_properties' =\u003e [],\n        'hide_properties' =\u003e [],\n        'id_properties' =\u003e [\n            'postId',\n        ],\n        'urls' =\u003e [\n            'self' =\u003e ['name' =\u003e 'get_post'], //named route\n        ],\n    ],\n    [\n        'class' =\u003e 'Acme\\Domain\\Dummy\\User',\n        'alias' =\u003e '',\n        'aliased_properties' =\u003e [],\n        'hide_properties' =\u003e [],\n        'id_properties' =\u003e [\n            'userId',\n        ],\n        'urls' =\u003e [\n            'self' =\u003e ['name' =\u003e 'get_user'], //named route\n            'friends' =\u003e ['name' =\u003e 'get_user_friends'], //named route\n            'comments' =\u003e ['name' =\u003e 'get_user_comments'], //named route\n        ],\n    ],\n    [\n        'class' =\u003e 'Acme\\Domain\\Dummy\\ValueObject\\UserId',\n        'alias' =\u003e '',\n        'aliased_properties' =\u003e [],\n        'hide_properties' =\u003e [],\n        'id_properties' =\u003e [\n            'userId',\n        ],\n        'urls' =\u003e [\n            'self' =\u003e ['name' =\u003e 'get_user'], //named route\n            'friends' =\u003e ['name' =\u003e 'get_user_friends'], //named route\n            'comments' =\u003e ['name' =\u003e 'get_user_comments'], //named route\n        ],\n    ],\n    [\n        'class' =\u003e 'Acme\\Domain\\Dummy\\Comment',\n        'alias' =\u003e '',\n        'aliased_properties' =\u003e [],\n        'hide_properties' =\u003e [],\n        'id_properties' =\u003e [\n            'commentId',\n        ],\n        'urls' =\u003e [\n            'self' =\u003e ['name' =\u003e 'get_comment'], //named route\n        ],\n    ],\n    [\n        'class' =\u003e 'Acme\\Domain\\Dummy\\ValueObject\\CommentId',\n        'alias' =\u003e '',\n        'aliased_properties' =\u003e [],\n        'hide_properties' =\u003e [],\n        'id_properties' =\u003e [\n            'commentId',\n        ],\n        'urls' =\u003e [\n            'self' =\u003e ['name' =\u003e 'get_comment'], //named route\n        ],\n    ],\n];\n\n```\n\n\nThe named routes belong to the `app/Http/routes.php`. Here's a sample for the routes provided mapping:\n\n**Laravel**\n\n```php\nRoute::get(\n  '/post/{postId}',\n  ['as' =\u003e 'get_post', 'uses' =\u003e 'PostController@getPostAction']\n);\n\nRoute::get(\n  '/post/{postId}/comments',\n  ['as' =\u003e 'get_post_comments', 'uses' =\u003e 'CommentsController@getPostCommentsAction']\n);\n\n//...\n```\n\n**Lumen**\n\n```php\n$app-\u003eget(\n  '/post/{postId}',\n  ['as' =\u003e 'get_post', 'uses' =\u003e 'PostController@getPostAction']\n);\n\n$app-\u003eget(\n  '/post/{postId}/comments',\n  ['as' =\u003e 'get_post_comments', 'uses' =\u003e 'CommentsController@getPostCommentsAction']\n);\n\n//...\n``` \n\nAll of this set up allows you to easily use the `JsonSerializer` service as follows:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers;\n\nuse Acme\\Domain\\Dummy\\PostRepository;\nuse NilPortugues\\Laravel5\\Json\\JsonSerializer;\nuse NilPortugues\\Laravel5\\Json\\JsonResponseTrait;\n\nclass PostController extends \\Laravel\\Lumen\\Routing\\Controller\n{\n    use JsonResponseTrait;\n\n    /**\n     * @var PostRepository\n     */\n    protected $postRepository;\n\n    /**\n     * @var JsonSerializer\n     */\n    protected $serializer;\n\n    /**\n     * @param PostRepository $postRepository\n     * @param JsonSerializer $jsonSerializer\n     */\n    public function __construct(PostRepository $postRepository, JsonSerializer $jsonSerializer)\n    {\n        $this-\u003epostRepository = $postRepository;\n        $this-\u003eserializer = $jsonSerializer;\n    }\n\n    /**\n     * @param int $postId\n     *\n     * @return \\Symfony\\Component\\HttpFoundation\\Response\n     */\n    public function getPostAction($postId)\n    {\n        $post = $this-\u003epostRepository-\u003efindById($postId);\n\n        /** @var \\NilPortugues\\Api\\Json\\JsonTransformer $transformer */\n        $transformer = $this-\u003eserializer-\u003egetTransformer();\n        $transformer-\u003esetSelfUrl(route('get_post', ['postId' =\u003e $postId]));\n        $transformer-\u003esetNextUrl(route('get_post', ['postId' =\u003e $postId+1]));\n\n        return $this-\u003eresponse($this-\u003eserializer-\u003eserialize($post));\n    }\n}\n```\n\n**Output:**\n\n```\nHTTP/1.1 200 OK\nCache-Control: protected, max-age=0, must-revalidate\nContent-type: application/json; charset=utf-8\n```\n\n```json\n{\n    \"post_id\": 9,\n    \"headline\": \"Hello World\",\n    \"body\": \"Your first post\",\n    \"author\": {\n        \"user_id\": 1,\n        \"name\": \"Post Author\"\n    },\n    \"comments\": [\n        {\n            \"comment_id\": 1000,\n            \"dates\": {\n                \"created_at\": \"2015-07-18T12:13:00+00:00\",\n                \"accepted_at\": \"2015-07-19T00:00:00+00:00\"\n            },\n            \"comment\": \"Have no fear, sers, your king is safe.\",\n            \"user\": {\n                \"user_id\": 2,\n                \"name\": \"Barristan Selmy\"\n            }\n        }\n    ],\n    \"links\": {\n        \"self\": {\n            \"href\": \"http://localhost:8000/post/9\"\n        },\n        \"next\": {\n            \"href\": \"http://localhost:8000/post/10\"\n        },\n        \"comments\": {\n            \"href\": \"http://localhost:8000/post/9/comments\"\n        }\n    }\n}\n```\n\n#### Response objects (JsonResponseTrait)\n\nThe following `JsonResponseTrait` methods are provided to return the right headers and HTTP status codes are available:\n\n```php\n    protected function errorResponse($json);\n    protected function resourceCreatedResponse($json);\n    protected function resourceDeletedResponse($json);\n    protected function resourceNotFoundResponse($json);\n    protected function resourcePatchErrorResponse($json);\n    protected function resourcePostErrorResponse($json);\n    protected function resourceProcessingResponse($json);\n    protected function resourceUpdatedResponse($json);\n    protected function response($json);\n    protected function unsupportedActionResponse($json);\n```\n\n\n\u003cbr\u003e\n## Quality\n\nTo run the PHPUnit tests at the command line, go to the tests directory and issue phpunit.\n\nThis library attempts to comply with [PSR-1](http://www.php-fig.org/psr/psr-1/), [PSR-2](http://www.php-fig.org/psr/psr-2/), [PSR-4](http://www.php-fig.org/psr/psr-4/) and [PSR-7](http://www.php-fig.org/psr/psr-7/).\n\nIf you notice compliance oversights, please send a patch via [Pull Request](https://github.com/nilportugues/laravel5-json-transformer/pulls).\n\n\n\u003cbr\u003e\n## Contribute\n\nContributions to the package are always welcome!\n\n* Report any bugs or issues you find on the [issue tracker](https://github.com/nilportugues/laravel5-json-transformer/issues/new).\n* You can grab the source code at the package's [Git repository](https://github.com/nilportugues/laravel5-json-transformer).\n\n\n\u003cbr\u003e\n## Support\n\nGet in touch with me using one of the following means:\n\n - Emailing me at \u003ccontact@nilportugues.com\u003e\n - Opening an [Issue](https://github.com/nilportugues/laravel5-json-transformer/issues/new)\n - Using Gitter: [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/nilportugues/laravel5-json-transformer?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge)\n\n\n\u003cbr\u003e\n## Authors\n\n* [Nil Portugués Calderó](http://nilportugues.com)\n* [The Community Contributors](https://github.com/nilportugues/laravel5-json-transformer/graphs/contributors)\n\n\n## License\nThe code base is licensed under the [MIT license](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilportugues%2Flaravel5-json","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnilportugues%2Flaravel5-json","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilportugues%2Flaravel5-json/lists"}