Download the PHP package lark/framework without Composer

On this page you can find all versions of the php package lark/framework. 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 framework

Lark Framework

Lark is a modern, lightweight app framework designed specifically for developing REST APIs.

Installation

Requirements:

Composer Install

Routing

The router is used to dispatch route actions and middleware.

Routes

There are multiple ways to define routes.

Regular Expression Routes

Regular expression routes use PCRE patterns for matching routes.

Route Groups

Route groups can be used to simplify defining similar routes.

Route Group Loading

Route groups can be defined in route files which are loaded during routing (lazy load routes).

Inside route files router() should only be called once to avoid false route no match errors.

Route Controller

A route controller object can be used with Route Group Loading.

Route Actions

Route actions are executed when a route is matched. Route actions can be a callable function (Closure) or array with [class, method]. The first route matched is the only route action that will be executed.

Route Not Found Action

If no route match is found a not found action can be defined. The HTTP response status code is auto set to 404.

If a not found action is not defined a Lark\Router\NotFoundException will be thrown.

Route Parameters

Named Parameters

Route named parameters are required parameters that do not use regular expressions. Multiple name parameters are allowed.

Optional Named Parameters

Route optional named parameters are optional parameters that do not use regular expressions. Optional named parameters can only be used at the end of the route. Multiple optional named parameters are allowed.

In this example the groupId parameter is optional, so route /users/5 and /users/5/10 would both match.

Regular Expression Parameters

Regular expressions can be used to define parameters using PCRE patterns. Multiple regular expression parameters are allowed.

Middleware

Middleware is a single or multiple actions that are executed before a route action is called. Middleware actions can be executed always or only when a route is matched. Middleware must be defined before routes are defined. Middleware actions follow the same structure as Route Actions. The arguments Lark\Request $req and Lark\Response $res are passed to all middleware actions.

Multiple middleware actions can be set.

Route Middleware

Route specific middleware actions are only executed if the route is matched.

If the HTTP request is /api/users then both the middleware action and route action would be executed.

Middleware Execution Order

Middleware is always executed in the following order:

  1. Always execute (router()->bind(...))
  2. Execute mapped on matched route (router()->map(...))
  3. Execute on matched route (router()->matched(...))
  4. After middleware (router()->after(...))

Route Group Middleware

Middleware can be defined to be used only on a specific route group. Route group middleware actions are only executed if a group route is matched.

After Middleware

After middlware always runs after a route action has been called, even if the route does not exist.

Logging

Lark\Logger is used for logging. The helper function logger() is available.

Logging info level record example.

Global context can be added to all context sent in log record.

Exception Handling

Exceptions can be handled using the exception handler.

Example App\ExceptionHandler class.

Debugger

Lark\Debugger can be used for debugging. The helper functions x() are available.

Configuration & Bindings

Framework configuration and bindings can be set with the use() method.

Debugging

Enable Lark internal append debugger info for debugger dump.

Enable Lark internal debug logging.

Database Connections

Database connections are registered using the syntax db.connection.[connectionId] and accessed using the syntax [connectionId]$[database]$[collection].

Read more in db().

Database Global Options

Database global options can be set using db.options. All default option values are listed below.

Read more about Write Concern in the MongoDB docs and in the PHP docs.

Database Sessions

Sessions can be stored in the database using a Lark\Model object.

Validator Custom Rules

Custom validator rules can be registered using validator.rule.[type].[ruleClassName].

Environment Variables & Configuration

Lark\Env is used for app environment variables and configuration. The helper function env() is available.

Example read PATH environment variable.

Example .env file.

Example .env file usage.

Other Lark\Env methods: fromArray(array $array), has(string $key): bool and toArray(): array.

Request

Lark\Request provides HTTP request data with input sanitizing. The helper function req() is available.

If HTTP header Content-Type: application/json does not exist for any JSON methods, an automatic response with HTTP status code 400 and JSON body {"message": "Invalid JSON: [reason]"} will be sent.

Individual JSON fields can also be accessed with sanitizing.

POST request ( Content-Type: application/x-www-form-urlencoded ) example.

GET request example.

Request cookie example.

Request Session

Lark\Request\Session is used to manage sessions.

Sessions can be stored in the database by using Lark\Database\Session::handler().

Lark\Request\SessionFlash can be used to store short-term data where the data is available from when set through the following request, example:

Request Methods

Request Input Methods

Input methods include methods for request input objects: Cookie, Input and Query.

Session Methods

Session methods clear(), get(), has() and set() all use dot notation for keys, for example: set('user.isActive', 1) equals: [user => [isActive => 1]].

Response

Lark\Response is used to control the HTTP response.

Response Methods

Database

Lark\Database is used to access MongoDB database and collection instances. The helper function db() is available.

Insert Documents

Find Documents

Update Documents

By default update methods used the $set operator for updates, like ['$set' => ['role' => 'admin]]. This operator can be changed, for example:

Replace Documents

Delete Documents

Collection Field Methods

Use dot notation for nested field names like field1.field2.

Database Methods

Database Field Methods

Schema

Lark\Schema is used to create schemas for creating entities, entity validation and database collection creation.

Schema uses Validation Types & Rules for field definitions.

Options for in $index and $indexes are any field starting with $, like $unique, and more options can be found in the MongoDB docs.

Default field values can also be set dynamically. For nested fields use dot notation like field.nestedfield.

Field value callbacks can be used. For nested fields use dot notation like field.nestedfield.

Field Schema Imports

A schema file can be imported as a schema for a schema field. First, create a partial schema in a schema file, for example: [DIR_SCHEMAS]/partials/users.info.php.

Next, add the import using a field name and file.

Printing $schema->toArray() will output:

Nested fields (using dot notation) can also be used.

Example partial schema in: [DIR_SCHEMAS]/partials/users.info.php:

Model

Lark\Model is a model: a way to simplify database calls and creating/validating entities.

The App\Model\User class can be used for creating an entity and validation.

The $mode argument can be used to change the validator mode, for example requiring document IDs with replace+id or update+id:

The $mode argument can be used to allow missing fields that can be used for partial documents with update or update+id:

The Model::db() method can be used to access the Model database collection (Model::DBS must be set).

Important: Model classes shouldn't have any required parameters in their Model::__construct() method, because the Models are automatically instantiated when using model/database binding, and any required parameters will not be present.

Model Schema Method

The Model::schema() method can be used in multiple ways. By default the method will use the Model::SCHEMA schema file constant to load the schema from file.

Another way to create a schema is overriding the parent method and passing the schema array:

The above method caches the schema object, so when the schema method is called again it returns the referenced Schema object.

A callback can also be passed to access the Schema object created by the parent method, example:

Model Database Query

The model Lark\Database\Query class can be used for input query parameters.

Query Selectors

Query selectors can be used as query parameters. Match a field with field value:

MongoDB comparison selectors $eq, $gt, $gte, $in, $lt, $lte, $ne and $nin can be used like:

With the $in selector:

With multiple selectors:

Query Options

By default queries with multiple selectors will perform a logical AND operation. A logical OR operation can be used with the $or option:

The $filter (or $projection) option can be used to filter the document fields returned from the database:

The $page option can be used for pagination.

By default the limit of documents per page is determined by the database option find.limit.

The default sort order of documents for the $page option is ["id" => 1], this can be overridden using the $sort option.

The $limit option can be used to set the number of documents returned or to override the default documents per page when using the $page option.

The $limit option value cannot exceed the database option find.limit value.

The $sort option can be used to set the sort order or documents.

The $skip option can be used to set the query skip value.

The $skip option will always be overridden when used with the $page option.

Auto Created and Updated Field Values

Created and updated field values can be used to auto set fields with created and updated date/times. Example schema:

Now the createdAt and updatedAt fields with be auto set to the current timestamp (time()). The values can be set to timestamp by default, or can be set to datetime for DateTime or dbdatetime for MongoDB\BSON\UTCDateTime, example:

In the above examples the createdAt field will be set once (using schema default value) and the updatedAt field will be set each time the document is made.

Database Model Schema Constraints

Database model schema constraints can be used as database constraints on references like verifying foreign keys and deleting documents by references.

Refs Foreign Key Constraint

The $refs.fk constraint verifies foreign keys, can be set in any model schema and is used with the Database methods: insert(), insertOne(), replaceBulk(), replaceId(), replaceOne(), update(), updateBulk(), updateId() and updateOne().

Example document in users.log:

Now when a model database insert/replace/update method is called the $refs.fk constraint above will verify the collection users.log field userId value exists as a foreign key in the users collection field id (_id).

If foreign key constraint verification fails a Lark\Database\Constraint\DatabaseConstraintException exception will be thrown with a message like Failed to insert or update document(s), foreign key constraint failed for "userId".

The $refs.fk foreign fields (foreignField) must always be a MongoDB ObjectId and foreign key verification on any other type will fail.

The $refs.fk constraint will always verify a foreign key, even when the local field value is null, but this can be disabled by using the nullable$ prefix on the local field name, like nullable$userId, which means all local field null values will not have the foreign key verified.

The $refs.fk constraint can also be used on an array of foreign keys in an array:

Example document in users.groups:

Now when a model database insert/replace/update method is called the $refs.fk constraint above will verify each value in the collection users.groups field users array exists as a foreign key in the users collection field id (_id).

The $refs.fk constraint can also be used on objects in an array that have foreign keys:

Example document in users.allowed

Now when a model database insert/replace/update method is called the $refs.fk constraint above will verify the collection users.allowed field users array to ensure each object field id value exists as a foreign key in the users collection field id (_id).

The $refs.fk constraint can be used with multiple collections and fields:

The $refs.fk constraint can also be used with the same model:

Refs Clear Constraint

The $refs.clear constraint allows clearing field values, can be set in any model schema and is used with the Database::deleteIds() method.

Example document in users.log:

Now when the model database method deleteIds() is called the $refs.clear constraint above will trigger a database clear (update operation) to clear all document userId fields in the users.log collection with userId: {$in: [ids]}.

The equivalent in MongoDB shell would be:

Refs Delete Constraint

The $refs.delete constraint allows deleting documents, can be set in any model schema and is used with the Database::deleteIds() method.

Example document in users.log:

Now when the model database method deleteIds() is called the $refs.delete constraint above will trigger a database delete operation to delete all documents in the users.log collection with userId: {$in: [ids]}.

The equivalent in MongoDB shell would be:

The $refs.delete constraint can also be used to pull ($pullAll) IDs from an array:

Example document in users.groups:

Now when the model database method deleteIds() is called the $refs.delete constraint above will trigger a database update operation to $pullAll IDs in the collection users.groups field users.

The equivalent in MongoDB shell would be:

Note: even when multiple values are pulled from an array on a single document field MongoDB will still return modifiedCount: 1

The $refs.delete constraint can also be used to pull ($pull) objects from an array based on an object field value:

Example document in users.allowed

Now when the model database method deleteIds() is called the $refs.delete constraint above will trigger a database update operation to $pull all objects in collection users.groups field users based on object field id value.

The equivalent in MongoDB shell would be:

Note: even when multiple objects are pulled from an array on a single document field MongoDB will still return modifiedCount: 1

The $refs.delete constraint can be used with multiple collections and fields:

Validator

Lark\Validator is used for validation and making entities.

Assertion can be used during validation.

Make entities with validation.

Validation Types & Rules

Rules notNull and notEmpty, and sometimes id, are rules for all types that do not allow the value to be null. The rule voidable can be used for any fields that can be missing.

Nested Fields

Nested fields can be defined using the fields property.

Nested Schemas

Nested schemas can be defined for an array of arrays or objects using the schema:array or schema:object property.

In the example above if the schema rule notEmpty is not used before the schema:array or schema:object property, and the array of arrays or objects is empty, no rules will be validated/asserted.

Partial documents are not allowed inside nested schema objects or arrays.

Assert Callback

A callback can be used with the assert() method.

Custom Validation Rule

Custom validation rules can be created.

It is also possible to override existing rules.

Filter

Lark\Filter is used for filtering values.

Filter by array keys.

Filter Methods

HTTP Client

Lark\Http\Client is an HTTP client.

Various HTTP methods are available.

Strings can also be used to send JSON.

Options can be set for all methods (will override default options).

Options can be set for individual methods (will override default options and options for all methods).

Options for curl can be set.

HTTP Client Options

CLI

Lark\Cli is used to create CLI apps.

Arguments and options can be set for a command, and each argument and option has optional settings.

The CLI Lark\Cli\Output class is used for output and styling output.

The output grid() method can be used to evenly space columns.

Above example would output:

Use confirm() for prompting.

Use input() for input.

CLI Methods

CLI Command Methods

CLI Output Propeties

CLI Output Methods

File

Lark\File is used to handle files.

Lark\Json\File is used for JSON files.

File Methods

Timer

Lark\Timer works as a timer.

Helpers

Helpers are global helper functions.

Helper app()

Access the main App instance using the app() function.

Helper db()

The db() function is a database collection instance helper.

Read more in Database Connections.

Helper dbdatetime()

The dbdatetime() function returns a MongoDB\BSON\UTCDateTime object.

Helper debug()

The debug() function is a debugger and logging helper. When called the debug() function will append the debugger info and send to logger (Logger::debug()).

Also see x() helper function.

Read more in Logging.

Helper env()

The env() function is an environment variables helper.

Read more in Environment Variables & Configuration.

Helper f()

The f() function returns a formatted string.

Helper halt()

The halt() function can be used to immediately return an HTTP response status code and optional JSON message.

Helper logger()

Access a Logger instance using the logger() function.

Read more in Logging.

Helper p()

The p() function outputs formatted (HTML/CLI) variables.

Helper pa()

The pa() function is a variable printer.

Helper req()

Access the Lark\Request instance using the req() function.

Read more in Request.

Helper res()

Access the Lark\Response instance using the res() function.

Read more in Response.

Helper router()

Access the Lark\Router instance using the router() function.

Read more in Routing.

Helper x()

The x() function is a debugger and dumper helper. When called the x() function (or Lark\Debugger::dump()) will dump all debugger info objects and stop execution.

Also see debug() helper function.

Read more in Debugger.


All versions of framework with dependencies

PHP Build Version
Package Version
Requires mongodb/mongodb Version ^1.9
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 lark/framework contains the following files

Loading the files please wait ....