Download the PHP package php-grape/grape-entity without Composer
On this page you can find all versions of the php package php-grape/grape-entity. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download php-grape/grape-entity
More information about php-grape/grape-entity
Files in php-grape/grape-entity
Package grape-entity
Short Description A simple facade for managing the relationship between your model and API.
License MIT
Homepage https://github.com/php-grape/grape-entity
Informations about the package grape-entity
Table of Contents
- PhpGrape\Entity
- Introduction
- Installation
- Example
- Reusable Responses with Entities
- Defining Entities
- Basic Exposure
- Exposing with a Presenter
- Conditional Exposure
- Safe Exposure
- Nested Exposure
- Collection Exposure
- Merge Fields
- Runtime Exposure
- Unexpose
- Overriding exposures
- Returning only the fields you want
- Aliases
- Format Before Exposing
- Expose null
- Default Value
- Documentation
- Options
- Passing Additional Option To Nested Exposure
- Attribute Path Tracking
- Using Entities
- JSON and XML formats
- Key transformer
- Adapters
- Laravel / Eloquent adapter
- Testing with Entities
- Contributing
- License
PhpGrape\Entity
Introduction
Heavily inspired by ruby-grape/grape-entity.
This package adds Entity support to API frameworks. PhpGrape's Entity is an API focused facade that sits on top of an object model.
While this can be achieved with Transformers (using Laravel), it provides a cleaner approach with more features.
Installation
Example
Reusable Responses with Entities
Entities are a reusable means for converting PhP objects to API responses. Entities can be used to conditionally include fields, nest other entities, and build ever larger responses, using inheritance.
Defining Entities
Entities inherit from PhpGrape\Entity
and use PhpGrape\EntityTrait
. Exposures can use runtime options to determine which fields should be visible, these options are available to 'if'
, and 'func'
.
PhP doesn't support multiple inheritance, so if you need your entities to inherits from multiple class use the extends
method
Example:
Basic Exposure
Define a list of fields that will always be exposed.
The field lookup takes several steps
- first try
entity-instance->exposure
- next try
entity-instance->exposure()
- next try
object->exposure
(magic__get
method included) - next try
object->exposure()
(magic__call
method included) - last raise a
MissingPropertyException
NOTE: protected and private properties/methods are exposed by default. You can change this behavior by setting one or all of these static properties to true:
Exposing with a Presenter
Don't derive your model classes from Grape::Entity
, expose them using a presenter.
Conditional Exposure
Use 'if'
to expose fields conditionally.
Safe Exposure
Don't raise an exception and expose as null, even if the field cannot be evaluated.
Nested Exposure
Supply a function to define an array using nested exposures.
You can also conditionally expose attributes in nested exposures:\
Collection Exposure
Use self::root(plural, singular = null)
to expose an object or a collection of objects with a root key.
By default every object of a collection is wrapped into an instance of your Entity
class.
You can override this behavior and wrap the whole collection into one instance of your Entity
class.
As example:
Merge Fields
Use 'merge'
option to merge fields into the array or into the root:
This will return something like:
It also works with collections:
Provide closure to solve collisions:
Runtime Exposure
Use a closure to evaluate exposure at runtime. The supplied function will be called with two parameters: the represented object and runtime options.
NOTE: A closure supplied with no parameters will be evaluated as a nested exposure (see above).
You can also use the 'func'
option, which is similar.
Only difference is, this option will also accept a string (representing the name of a function), which can be convenient sometimes.
You can also define a method or a property on the entity and it will try that before trying on the object the entity wraps.
You always have access to the presented instance (object
) and the top-level
entity options (options
).
Unexpose
To undefine an exposed field, use the method. Useful for modifying inherited entities.
Overriding exposures
If you want to add one more exposure for the field but don't want the first one to be fired (for instance, when using inheritance), you can use the override
flag. For instance:
User
will return something like this { "name" : "John" }
while Employee
will present the same data as { "employee_name" : "John" }
instead of { "name" : "John", "employee_name" : "John" }
.
Returning only the fields you want
After exposing the desired attributes, you can choose which one you need when representing some object or collection by using the only: and except: options. See the example:
This will return something like this:
Instead of returning all the exposed attributes.
The same result can be achieved with the following exposure:
Aliases
Expose under a different name with 'as'
.
Format Before Exposing
Apply a formatter before exposing a value.
Defining a reusable formatter between multiples entities:
Expose Null
By default, exposures that contain null
values will be represented in the resulting JSON.
As an example, an array with the following values:
will result in a JSON object that looks like:
There are also times when, rather than displaying an attribute with a null
value, it is more desirable to not display the attribute at all. Using the array from above the desired JSON would look like:
In order to turn on this behavior for an as-exposure basis, the option expose_null
can be used. By default, expose_null
is considered to be true
, meaning that null
values will be represented in JSON. If false
is provided, then attributes with null
values will be omitted from the resulting JSON completely.
expose_null
is per exposure, so you can suppress exposures from resulting in null
or express null
values on a per exposure basis as you need:
It is also possible to use expose_null
with withOptions
if you want to add the configuration to multiple exposures at once.
When using withOptions
, it is possible to again override which exposures will render null
by adding the option on a specific exposure.
Default Value
This option can be used to provide a default value in case the return value is null or false or empty (string or array).
Documentation
Expose documentation with the field. Gets bubbled up when used with various API documentation systems.
Options
The option key 'collection'
is always defined. The 'collection'
key is boolean, and defined as true
if the object presented is iterable, false
otherwise.
Any additional options defined on the entity exposure are included as is. In the following example user
is set to the value of current_user
.
Passing Additional Option To Nested Exposure
Sometimes you want to pass additional options or parameters to nested a exposure. For example, let's say that you need to expose an address for a contact info and it has two different formats: full and simple. You can pass an additional full_format
option to specify which format to render.
Notice: In the above code, you should pay attention to Safe Exposure yourself. For example, $instance->address
might be null
and it is better to expose it as null directly.
Attribute Path Tracking
Sometimes, especially when there are nested attributes, you might want to know which attribute is being exposed. For example, some APIs allow users to provide a parameter to control which fields will be included in (or excluded from) the response.
PhpGrape\Entity can track the path of each attribute, which you can access during conditions checking
or runtime exposure via $options['attr_path']
.
The attribute path is an array. The last item of this array is the name (alias) of current attribute. If the attribute is nested, the former items are names (aliases) of its ancestor attributes.
Example:
Using Entities
Example of API controller.
JSON and XML formats
PhpGrape\Entity implements JsonSerializable, so calling json_encode
will automatically serialize your entity to JSON.
It'll work in any circumstances (see Using Entities):
2 helpers are also presents on PhpGrape\Entity:
- toJson
- toXml
So you can do:
Note: When ::represent
returns a single entity, you'll also be able to call these methods. It means it won't work it you set a root
key or if you do not use presentCollection
properly when presenting a collection (see Collection Exposure)
Key transformer
Most of the time backend languages use different naming conventions than frontend ones, so you often end up using helpers to convert your data keys case.
transformKeys
helps you deal with that:
As a bonus, 2 case helpers are already included: camel
& snake
(handling 'UTF-8' unicode characters)
Example :
Adapters
For many reasons, you might need to access your properties / methods in a certain way. Or redefine the field lookup priority for instance (see Basic Exposure). PhpGrape\Entity lets you write your own adapter depending on your needs.
Adapter structure:
To remove an adapter, simply set it to null:
NOTE: adapter names are unique. Using the same name will override previous adapter.
Laravel / Eloquent adapter
Eloquent relies massively on the magic __get
method. Unfortunately, no Exception is thrown in case you access an undefined property, which is quite inconvenient in some situations. It doesn't help either with options like safe
or expose_null
.
To fix this, and to enjoy all the great PhpGrape\Entity features, an Eloquent
adapter's been included. You'll still be able to use magic attributes, mutated attributes and access relations in your exposures. No more typo allowed though!
Works with all Laravel versions!
Note: when creating a model, if all attributes are not passed, you'll need to call the fresh
method in order to retrieve them.
Testing with Entities
Test API request/response as usual.
Contributing
See CONTRIBUTING.md.
License
MIT License. See LICENSE for details.