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.
Download lark/framework
More information about lark/framework
Files in lark/framework
Package framework
Short Description Lark Framework
License MIT
Homepage https://github.com/shayanderson/lark-framework
Informations about the package framework
Lark Framework
Lark is a modern, lightweight app framework designed specifically for developing REST APIs.
- Installation
- Routing
- Routes
- Route Parameters
- Route Actions
- Middleware
- Logging
- Exception Handling
- Debugger
- Configuration & Bindings
- Environment Variables & Configuration
- Request
- Response
- Database
- Schema
- Model
- Validator
- Validation Types & Rules
- Filter
- HTTP Client
- CLI
- File
- Timer
- Helpers
x()
Installation
Requirements:
- PHP 8
- PHP extensions
- Required
- [...]
- Optional
- curl - if using
Lark\Http\Client
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:
- Always execute (
router()->bind(...)
) - Execute mapped on matched route (
router()->map(...)
) - Execute on matched route (
router()->matched(...)
) - 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 code400
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
body(bool $convertHtmlEntities = true): string
- request raw body data gettercontentType(): string
- content-type gettercookie(string $key, $default = null): Lark\Request\Cookie
- cookie input object getterhasHeader(string $key): bool
- check if header key existsheader(string $key): string
- header value getterheaders(): array
- get all headershost(): string
- HTTP host value getter, likewww.example.com
input(string $key, $default = null): Lark\Request\Input
- input object getter forPOST
ipAddress(): string
- IP address getterisContentType(string $contentType): bool
- validate request content-typeisMethod(string $method): bool
- validate request methodisSecure(): bool
- check if request is secure (HTTPS)json()
- JSON request body getterjsonArray(): array
- JSON request body getter, must be array or400
HTTP status code responsejsonField(string $field, $default = null): Lark\Request\Json
- JSON request field object getterjsonObject(): array
- JSON request body getter, must be object or400
HTTP status code responsemethod(): string
- request method getterpath(): string
- path getter, like/the/path
pathWithQueryString(): string
- path with query string getter, like/the/path?x=1
port(): int
- port getterquery(string $key, $default = null): Lark\Request\Query
- query input object getter forGET
queryString(): string
- query string getter, likex=1&y=2
scheme(): string
- URI scheme getter, likehttp
session(): Lark\Request\Session
- session object getteruri(): string
- URI getter, likehttp://example.com/example?key=x
Request Input Methods
Input methods include methods for request input objects: Cookie
, Input
and Query
.
email(array $options = [])
- value getter, sanitize as emailfloat(array $options = ['flags' => FILTER_FLAG_ALLOW_FRACTION])
- value getter, sanitize as floathas(): bool
- check if key existsinteger(array $options = [])
- value getter, sanitize as integerstring(array $options = [])
- value getter, sanitize as stringurl(array $options = [])
- value getter, sanitize as URL
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]]
.
clear(string $key)
- clear a keystatic cookieOptions(array $options)
- set cookie options- default options are:
['lifetime' => 0, 'path' => '/', 'domain' => '', 'secure' => false, 'httponly' => false]
- default options are:
destroy()
- destroy a sessionstatic exists(): bool
- check if sessions are enabled and session existsget(string $key)
- value getterhas(string $key): bool
- check if key existsid(): ?string
- session ID getterisSession(): bool
- check if session existsset(string $key, $value)
- key/value settertoArray(): array
- session array getter
Response
Lark\Response
is used to control the HTTP response.
Response Methods
cacheOff(): Lark\Response
- disable cache using cache-controlcontentType(string $contentType): Lark\Response
- content-type settercookie($key, $value, $expires, $path, $domain, $secure, $httpOnly): bool
- cookie settercookieClear(string $key, string $path = '/'): bool
- remove cookieheader(string $key, $value): Lark\Response
- header setterheaderClear(string $key): Lark\Response
- remove header keyheaders(array $headers): Lark\Response
- headers setter using arrayjson($data)
- respond with JSON payload (and content-typeapplication/json
in headers)redirect(string $location, bool $statusCode301 = false)
- send redirectsend($data)
- respond with raw data payloadcode(int $code): Lark\Response
- response status code setter
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
collectionField(string $field): Database\Field
- collection field object gettercount(array $filter = [], array $options = []): int
- count documents matching filterdelete(array $filter, array $options = []): int
- delete documents matching filterdeleteAll(array $options = []): int
- delete all documentsdeleteIds(array $ids, array $options = []): int
- delete documents by IDdeleteOne(array $filter, array $options = []): int
- delete single document matching filterdrop(): bool
- drop collectionexists(): bool
- check if collection existsfind(array $filter = [], array $options = []): array
- find documents matching filterfindId($id, array $options = []): ?array
- find document by IDfindIds(array $ids, array $options = []): array
- find documents by IDfindOne(array $filter = [], array $options = []): ?array
- find single document matching filterhas(array $filter, array $options = []): bool
- check if documents matching filter existhasIds(array $ids, array $options = []): bool
- check if documents with IDs existinsert(array $documents, array $options = []): array
- insert documentsinsertOne($document, array $options = []): ?string
- insert single documentping(): bool
- ping commandreplaceBulk(array $documents, array $options = []): int
- bulk replacereplaceId($id, $document, array $options = []): int
- replace single documentreplaceOne(array $filter, $document, array $options = []): int
- replace single documentupdate(array $filter, $update, array $options = []): int
- update documents matching filterupdateBulk(array $documents, array $options = []): int
- bulk updateupdateId($id, $update, array $options = []): int
- update document by IDupdateOne(array $filter, $update, array $options = []): int
- update single document matching filter
Database Field Methods
create($defaultValue = null): int
- create field with default valuedelete(): int
- delete collection fieldexists(bool $allDocs = true): bool
- check if field exists or checks if field exists on any document if!$allDocs
pull(array $filter, $value): int
- remove value from field arraypush(array $filter, $value, $unique = true): int
- append value to field array, if$unique
will only append value if doesn't already exist in field arrayrename(string $newName): int
- rename field
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 optionfind.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 likeFailed to insert or update document(s), foreign key constraint failed for "userId"
.The
$refs.fk
foreign fields (foreignField
) must always be a MongoDBObjectId
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 isnull
, but this can be disabled by using thenullable$
prefix on the local field name, likenullable$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.
- any type (default) - any type allowed
notNull
- value cannot benull
array
(orarr
) - value can bearray
ornull
allowed
- array values must be allowed[allowed => [...]]
length
- number of array items must be[length => x]
max
- array values cannot exceed maximum value of[max => x]
min
- array values cannot be lower than minimum value of[min => x]
notEmpty
- must be a non-emptyarray
notNull
- must be anarray
unique
- array values must be unique
boolean
(orbool
) - must beboolean
ornull
notNull
- must beboolean
datetime
- must be an instance ofDateTime
ornull
notNull
- must be instance ofDateTime
dbdatetime
- must be an instance ofMongoDB\BSON\UTCDateTime
ornull
notNull
- must be instance ofMongoDB\BSON\UTCDateTime
float
- must be afloat
ornull
between
- must be between both values[between => [x, y]]
max
- must be a maximum value of[max => x]
min
- must be a minimum value of[min => x]
notEmpty
- must be afloat
greater than zeronotNull
- must be afloat
integer
(orint
) - must be aninteger
ornull
between
- must be between both values[between => [x, y]]
id
- must be aninteger
whenENTITY_FLAG_ID
flag is setmax
- must be a maximum value of[max => x]
min
- must be a minimum value of[min => x]
notEmpty
- must be aninteger
greater than zeronotNull
- must be aninteger
number
(ornum
) - must be a number ornull
between
- must be between both values[between => [x, y]]
id
- must be a number whenENTITY_FLAG_ID
flag is setmax
- must be a maximum value of[max => x]
min
- must be a minimum value of[min => x]
notEmpty
- must be a number greater than zeronotNull
- must be a number
object
(orobj
) - must be anobject
ornull
notEmpty
- must be a non-emptyobject
notNull
- must be anobject
string
(orstr
) - must be astring
ornull
allowed
- value must be allowed[allowed => [...]]
alnum
- must only contain alphanumeric characters- or, must only contain alphanumeric characters and whitespaces
[alnum => true]
alpha
- must only contain alphabetic characters- or, must only contain alphabetic characters and whitespaces
[alpha => true]
contains
- must contain value[contains => x]
- or, must contain value (case-insensitive)
[contains => [x, true]]
email
- must be a valid email addresshash
- hashes must be equal (timing attack safe)[hash => x]
id
- must be anstring
whenENTITY_FLAG_ID
flag is setipv4
- must be valid IPv4 addressipv6
- must be valid IPv6 addressjson
- must be a valid JSONlength
- length must be number of characters[length => x]
regex
- value must be a regular expression match[regex => x]
max
- length must be a maximum number of characters[max => x]
min
- length must be a minimum number of characters[min => x]
notAllowed
- value must be allowed[notAllowed => [...]]
notEmpty
- must be a non-emptystring
notNull
- must be astring
password
- passwords must match[password => x]
url
- must be a valid URL
timestamp
- must be a timestamp ornull
notNull
- must be a timestamp
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 theschema:array
orschema: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
email($value, array $options = []): string
- sanitize value with email filterfloat($value, array $options = ['flags' => FILTER_FLAG_ALLOW_FRACTION]): float
- sanitize value with float filterinteger($value, array $options = []): int
- sanitize value with integer filterkeys(array $array, array $filter): array
- filters keys based on include or exclude filterstring($value, array $options = ['flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH]): string
- sanitize value with string filterurl($value, array $options = []): string
- sanitize value with url filter
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
curl
- set options forcurl
usingCURLOPT_[...]
optionsheaders
- set HTTP headers, which can be set using two methods['headers' => ['My-Header' => 'value']]
['headers' => ['My-Header: value']]
port
- set a custom port numberproxy
- use an HTTP proxyredirects
- allow redirectstimeout
- timeout in seconds for connection and executionurl
- base URL for request methodsverify
- verify peer's certificate and common name
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
abort($status = 0)
- display command aborted message and exit appcommand(string $name, string $description, array $aliases = []): Command
- register a commandconfirm(string $question, bool $isDefaultYes = false)
- confirm yes/noexit($status = 0)
- exit appheader(callable $callback)
- register a header callback used inthelp()
methodhelp()
- display help (auto invoked byCli
)input(string $text, $default = null)
- inputoption(string $option, string $description, callable $action)
- set global optionoutput()
- CLIOutput
object getterrun()
- run CLI app
CLI Command Methods
action($callbackOrClassArray): Command
- set command actionarg(string $arg, string $description, array $options = []): Command
- set argument- Options:
array
- argument with multiple values (must be last in arguments list)default
- default value, like:['default' => 'the value']
optional
- argument is optional
option(string $option, string $description = '', array $options = []): Command
-set option- Options:
default
- default value, like:['default' => 'the value']
CLI Output Propeties
bgBlack
- style background blackbgBlue
- style background bluebgCyan
- style background cyanbgGray
- style background graybgGreen
- style background greenbgPurple
- style background purplebgRed
- style background redbgWhite
- style background whitebgYellow
- style background yellowbgLigthBlue
- style background light bluebgLightCyan
- style background light cyanbgLightGray
- style background light graybgLightGreen
- style background light greenbgLightPurple
- style background light purplebgLightRed
- style background light redbgLightYellow
- style background light yellowcolorBlack
- style color blackcolorBlue
- style color bluecolorCyan
- style color cyancolorGray
- style color graycolorGreen
- style color greencolorPurple
- style color purplecolorRed
- style color redcolorWhite
- style color whitecolorYellow
- style color yellowcolorLigthBlue
- style color light bluecolorLightCyan
- style color light cyancolorLightGray
- style color light graycolorLightGreen
- style color light greencolorLightPurple
- style color light purplecolorLightRed
- style color light redcolorLightYellow
- style color light yellowstyleBlink
- style blinkingstyleBold
- style boldstyleDim
- style dimstyleHidden
- style hiddenstyleInvert
- style invertstyleUnderline
- style underline
CLI Output Methods
dim(string $text, string $end = PHP_EOL): Output
- print dim style textecho(string $text = '', string $end = PHP_EOL): Output
- Print text to stdouterror(string $text, string $end = PHP_EOL): Output
- print error textgrid(array $data, array $options = []): Output
- print grid- Options:
indent
- number of spaces to indentpadding
- column padding (default:4
)style
- apply style to column, like['style' => ['name' => 'colorBlue']]
info(string $text, string $end = PHP_EOL): Output
- print info textok(string $text, string $end = PHP_EOL): Output
- print success textwarn(string $text, string $end = PHP_EOL): Output
- print warning textstatic register(string $name, callable $callback)
- register style methodstderr(string $text, string $end = PHP_EOL): Output
- output to stderrstdout(string $text = '', string $end = PHP_EOL): Output
- output to stdoutstyleIndent(int $number): Output
- indent style
File
Lark\File
is used to handle files.
Lark\Json\File
is used for JSON files.
File Methods
delete(): bool
- delete a fileexists(): bool
- check if file existsexistsOrException()
- if file does not exist throw exceptionpath(): string
- file path getterread()
- read file contentswrite($data, $append = false, $lock = true): bool
- write file contents
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.