Download the PHP package grefon/mongo-model without Composer

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

MongoModel

GitHub Workflow Status GitHub release (latest by date) Packagist PHP Version

на русском

MongoModel allows you to conveniently work with MongoDB documents, as with objects.

Implemented:

MongoModel work with MongoDB PHP Library



Getting Started

Composer

Install this package through Composer. Edit require in your composer.json:

and run composer update

or

run this command in your command line:

Initialization of connection

The MongoDB class with debugging enabled will log requests and their status to the MongoDB::$trace.

Your first model

Create collection users in MongoDB.

Create new PHP Class User extends ModelMongoDB:

Each model class must extend ModelMongoDB. It must contain 4 main static variables:

$fieldsModel

In $fieldsModel the data model is described as an associative array. The key is the name of the object's property, the value is an array of the property's attributes.

The first value in an attribute array must always be the data type.

Type Description
string string
boolean or bool boolean true or false
int number
float floating point number
datetime in PHP will be a string (2022-10-03 11:27:15), and MongoDB will store the timestamp ISODate
array array
object object; in PHP it is stdClass
history array with history of changes

When data is loaded from MongoDB or saved, object properties will be typification.

All subsequent attributes in the array are free, but some of them are reserved:

Attribute Description
required Required object property. If the property value is not specified, then when trying to save the data throw new Exception
default Default value. For example: 'rating' => ['int', 'default' => 100]
timeCreate Can only be used on the datetime type. Sets the current time if is new object.
timeUpdate Can only be used on the datetime type. Sets the current time each time an object is saved by a method save().
onlyCreation Creates a variable in the MongoDB document on first save and no longer updates the data in it. Useful when the data in this property is updated in a third party process by direct requests.
hidden Hide a property on a method getArray
history Write changes to this property to history.
historyPrepare Specifies the method to check if the property has changed.
historyValue Specifies a method that returns the standardized property value for history.

Creating a new object

Example: examples/new.php

or

or

or

Each of these examples will create a new document in MongoDB:

It is also possible to create documents with your own ID:

If the ID is 24 characters long, then an attempt will be made to convert the string to ObjectId.

In the static method User::new(array $data, bool $returnID = true) the data array is passed as the first argument, the second - whether only the ID of the created document or the entire instance of the object should be returned; $returnID = false - return the entire object.


Operations with an object

Loading

YourModelClass::get($data)

Example: examples/get.php

By ID

By properties

When loading by properties, a check is made for the existence of the required fields name and rating in $fieldsModel. It is possible to search by internal properties if there is a dot in the key:

You can also search MongoDB syntax if the key starts with $:

If the document is not found in MongoDB User::get will return null.

Method save

save(array $data = null)

Example: examples/save.php

The method saves the current object instance to a MongoDB document. Only changed properties are sent to the database.

If the object is updated and not created for the first time, then properties with the onlyCreation attribute are ignored, while those with the history attribute are checked for changes and written to the history.

Method saveField

saveField(string $field, $value = '__EMPTY__')

Example: examples/save.php

Store in MongoDB only one property of the current object.

Light saving method. History of changes is not created. The timeUpdate property is not updated automatically.

or

Even though you have changed email its new value will not be written to MongoDB. Only the rating value will be saved to the database.

Method saveFields

saveFields($fields = null)

Example: examples/save.php

Save only specific properties of the current object to MongoDB.

Light saving method. History of changes is not created. The timeUpdate property is not updated automatically.

In your own methods of the User class, you can append to the protected changedFields array:

Method delete

delete()

Example: examples/delete.php

Delete a document from MongoDB.

Method getArray

getArray($includeField = null, bool $skipHidden = true)

Example: examples/getArray.php

The getArray method by default does not return properties that have hidden in the $fieldsModel. You can disable this by passing $skipHidden = false.

$includeField

You can pass a single attribute or an array of attributes that are specified for properties in $fieldsModel. For example:

Loading with cache

YourModelClass::getFromCache($data)

Example: examples/getFromCache.php

When loading with caching, the object instance is stored in memory and when reloading, there is no call to MongoDB. As in the get() method, you can load by ID or properties.

Useful when working with an object in different parts of the code.


Operations with objects

Method itemsGet

YourModelClass::itemsGet($data = null, $fields = null, $orderBy = null, $limited = null, array $settings = [])

Example: examples/itemsGet.php

Find documents in MongoDB and return an array of object instances or their defined properties.

Search data

$data

The search works in the same way as on the get() method, but the result is always an array with all found documents.

Return fields

$fields

If $fields = null then itemsGet will return an array of object instances. With each instance, you can perform the same actions as if it were processed after loading.

If a property is passed to $fields as a string, then an associative array with the specified property will be returned as a result of itemsGet.

If you pass an array of properties to $fields, then an associative array will be returned to the itemsGet result, where the key will be _id, and the value stdClass with the specified fields.

Sorting

$orderBy

Specify the field by which you want to sort documents when searching.

Pagination

$limited

Specify the number of documents to be searched and the indent (skip and limit).

Request settings

$settings

Settings for searching in MongoDB. For example, you can suggest an index:

Also in the settings you can pass more complex conditions for sorting by several fields.

Method itemsHas

YourModelClass::itemsHas($data = null)

Example: examples/itemsHas.php

Check if documents exist in the collection according to given conditions.

In $data is passed itemsGet method.

Returns true or false.

Method itemsCount

YourModelClass::itemsCount($data = null, array $settings = [])

Example: examples/itemsCount.php

Returns the number of documents matching the query.

In $data is passed itemsGet method.

In $settings - request-settings

Method itemsDelete

YourModelClass::itemsDelete($data = null)

Example: examples/itemsDelete.php

Removes all documents matching the query from the collection.

In $data is passed itemsGet method.

Returns the number of deleted documents.

Method itemsNew

YourModelClass::itemsNew(array $items, bool $returnID = true)

Example: examples/itemsNew.php

Creates several objects and inserts insertMany into MongoDB.

The method is similar YourModelClass::new(), with the only difference that the first argument is an array of data arrays.

Returns array of IDs of created objects, or array of objects (if $returnID = false).


History of changes

When an object is saved using the save() method, a history of changes is created. The history is written to an object property of type history. Properties that have history in their attributes are checked for change.

If the properties of an object with the history attribute have changed, then an entry will be added to the history array with the date of the change and a changes object listing all the changed properties. Each property is an array with two elements array(old value, new value).

Attribute historyPrepare

In the historyPrepare attribute, you can specify your method, which will be used to compare old value === new value.

Besides comparing simple data types (string, int, float, bool) there are 2 methods:

Your own method from the historyPrepare attribute and to the historyPrepareArray and historyPrepareObject methods will be passed two values: 1) value to be standardized somehow 2) an optional variable from the attribute value after the colon. For example, number will be passed to 'historyPrepare' => 'historyPrepareArray:number'

Let's imagine that the user has a phones property - it's an array of stdClass objects with phones:

From the given example 'historyPrepare' => 'historyPrepareArray:number' the phone array will be compared by the number field. When saved, the historyPrepareArray method converts the comparison data to the string [127774477,1555331188]. The same conversion will be performed on data from snapshot after the last save. Further comparison and record in history if there are changes.

Attribute historyValue

Your custom method that will process and return the value to write to the history.

See example: examples/User.php

Method checkRecordHistory

checkRecordHistory(array $changes)

Returns true by default; If it returns false - the history of changes will not be added.

Called during save when the history of changes has already been compiled.

In $changes is passed current changes.

The method is useful if you need to keep a history of changes, but under some circumstances sometimes do not record it.

For example, you can check the size of the current history and not write more than 100 entries:


To help the developer

Triggers

Method Description
afterCreate Called after class initialization in __construct.
afterLoad Called after loading data from MongoDB.
preSave Called before saving.
afterSave Called after saving. The method is passed an array of property names that have changed and been submitted to MongoDB.

Snapshots

getSnapshot($field) and getSnapshotUpdate($field)

After loading data from MongoDB, created a snapshot of current state. In the process, you may need to find out what data was in the database or since the last save.

Method getCollection

YourModelClass::getCollection()

Returns a MongoDB collection. Can be used for direct queries.

Method collectionInfo

MongoDB::collectionInfo(string $collection)

Example: examples/collectionInfo.php

Returns information about the collection.


All versions of mongo-model with dependencies

PHP Build Version
Package Version
Requires php Version >=7.3
ext-json Version *
ext-mongodb Version *
ext-mbstring Version *
mongodb/mongodb Version ^1.5.1
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 grefon/mongo-model contains the following files

Loading the files please wait ...