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.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package grape-entity

Coverage Status php-grape

Table of Contents

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

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:

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.


All versions of grape-entity with dependencies

PHP Build Version
Package Version
Requires php Version >=7.4.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package php-grape/grape-entity contains the following files

Loading the files please wait ....