• Stars
    star
    148
  • Rank 249,983 (Top 5 %)
  • Language
    PHP
  • License
    Other
  • Created almost 10 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[READ-ONLY] A flexible, lightweight and powerful Object-Relational Mapper for PHP, implemented using the DataMapper pattern. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

Total Downloads License

CakePHP ORM

The CakePHP ORM provides a powerful and flexible way to work with relational databases. Using a datamapper pattern the ORM allows you to manipulate data as entities allowing you to create expressive domain layers in your applications.

Database engines supported

The CakePHP ORM is compatible with:

  • MySQL 5.1+
  • Postgres 8+
  • SQLite3
  • SQLServer 2008+
  • Oracle (through a community plugin)

Connecting to the Database

The first thing you need to do when using this library is register a connection object. Before performing any operations with the connection, you need to specify a driver to use:

use Cake\Datasource\ConnectionManager;

ConnectionManager::setConfig('default', [
	'className' => \Cake\Database\Connection::class,
	'driver' => \Cake\Database\Driver\Mysql::class,
	'database' => 'test',
	'username' => 'root',
	'password' => 'secret',
	'cacheMetadata' => true,
	'quoteIdentifiers' => false,
]);

Once a 'default' connection is registered, it will be used by all the Table mappers if no explicit connection is defined.

Using Table Locator

In order to access table instances you need to use a Table Locator.

use Cake\ORM\Locator\TableLocator;

$locator = new TableLocator();
$articles = $locator->get('Articles');

You can also use a trait for easy access to the locator instance:

use Cake\ORM\Locator\LocatorAwareTrait;

$articles = $this->getTableLocator()->get('Articles');

By default, classes using LocatorAwareTrait will share a global locator instance. You can inject your own locator instance into the object:

use Cake\ORM\Locator\TableLocator;
use Cake\ORM\Locator\LocatorAwareTrait;

$locator = new TableLocator();
$this->setTableLocator($locator);

$articles = $this->getTableLocator()->get('Articles');

Creating Associations

In your table classes you can define the relations between your tables. CakePHP's ORM supports 4 association types out of the box:

  • belongsTo - E.g. Many articles belong to a user.
  • hasOne - E.g. A user has one profile.
  • hasMany - E.g. A user has many articles.
  • belongsToMany - E.g. An article belongsToMany tags.

You define associations in your table's initialize() method. See the documentation for complete examples.

Reading Data

Once you've defined some table classes you can read existing data in your tables:

use Cake\ORM\Locator\LocatorAwareTrait;

$articles = $this->getTableLocator()->get('Articles');
foreach ($articles->find() as $article) {
	echo $article->title;
}

You can use the query builder to create complex queries, and a variety of methods to access your data.

Saving Data

Table objects provide ways to convert request data into entities, and then persist those entities to the database:

use Cake\ORM\Locator\LocatorAwareTrait;

$data = [
	'title' => 'My first article',
	'body' => 'It is a great article',
	'user_id' => 1,
	'tags' => [
		'_ids' => [1, 2, 3]
	],
	'comments' => [
		['comment' => 'Good job'],
		['comment' => 'Awesome work'],
	]
];

$articles = $this->getTableLocator()->get('Articles');
$article = $articles->newEntity($data, [
	'associated' => ['Tags', 'Comments']
]);
$articles->save($article, [
	'associated' => ['Tags', 'Comments']
])

The above shows how you can easily marshal and save an entity and its associations in a simple & powerful way. Consult the ORM documentation for more in-depth examples.

Deleting Data

Once you have a reference to an entity, you can use it to delete data:

$articles = $this->getTableLocator()->get('Articles');
$article = $articles->get(2);
$articles->delete($article);

Meta Data Cache

It is recommended to enable metadata cache for production systems to avoid performance issues. For e.g. file system strategy your bootstrap file could look like this:

use Cake\Cache\Engine\FileEngine;

$cacheConfig = [
   'className' => FileEngine::class,
   'duration' => '+1 year',
   'serialize' => true,
   'prefix'    => 'orm_',
];
Cache::setConfig('_cake_model_', $cacheConfig);

Cache configs are optional, so you must require cachephp/cache to add one.

Creating Custom Table and Entity Classes

By default, the Cake ORM uses the \Cake\ORM\Table and \Cake\ORM\Entity classes to interact with the database. While using the default classes makes sense for quick scripts and small applications, you will often want to use your own classes for adding your custom logic.

When using the ORM as a standalone package, you are free to choose where to store these classes. For example, you could use the Data folder for this:

<?php
// in src/Data/Table/ArticlesTable.php
namespace Acme\Data\Table;

use Acme\Data\Entity\Article;
use Acme\Data\Table\UsersTable;
use Cake\ORM\Table;

class ArticlesTable extends Table
{
    public function initialize()
    {
        $this->setEntityClass(Article::class);
        $this->belongsTo('Users', ['className' => UsersTable::class]);
    }
}

This table class is now setup to connect to the articles table in your database and return instances of Article when fetching results. In order to get an instance of this class, as shown before, you can use the TableLocator:

<?php
use Acme\Data\Table\ArticlesTable;
use Cake\ORM\Locator\TableLocator;

$locator = new TableLocator();
$articles = $locator->get('Articles', ['className' => ArticlesTable::class]);

Using Conventions-Based Loading

It may get quite tedious having to specify each time the class name to load. So the Cake ORM can do most of the work for you if you give it some configuration.

The convention is to have all ORM related classes inside the src/Model folder, that is the Model sub-namespace for your app. So you will usually have the src/Model/Table and src/Model/Entity folders in your project. But first, we need to inform Cake of the namespace your application lives in:

<?php
use Cake\Core\Configure;

Configure::write('App.namespace', 'Acme');

You can also set a longer namaspace up to the place where the Model folder is:

<?php
use Cake\Core\Configure;

Configure::write('App.namespace', 'My\Log\SubNamespace');

Additional Documentation

Consult the CakePHP ORM documentation for more in-depth documentation.

More Repositories

1

cakephp

CakePHP: The Rapid Development Framework for PHP - Official Repository
PHP
8,677
star
2

phinx

PHP Database Migrations for Everyone
PHP
4,463
star
3

chronos

A standalone DateTime library originally based off of Carbon
PHP
1,347
star
4

debug_kit

Debug Toolbar for CakePHP applications.
PHP
853
star
5

docs

CakePHP CookBook
Makefile
677
star
6

app

CakePHP application template
PHP
371
star
7

cakephp-codesniffer

CakePHP Code Sniffer
PHP
238
star
8

datasources

CakePHP Datasources
PHP
237
star
9

localized

I18n and L10n related CakePHP code
PHP
214
star
10

migrations

CakePHP database migrations plugin
PHP
136
star
11

utility

[READ-ONLY] CakePHP Utility classes such as Inflector, Text, Hash, Security and Xml. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp
PHP
119
star
12

authentication

Authentication plugin for CakePHP. Can also be used in PSR7 based applications.
PHP
115
star
13

api_generator

[Unmaintained] Official CakePHP API Generator Git Repository
PHP
113
star
14

acl

Plugin for managing ACL in CakePHP applications.
PHP
111
star
15

upgrade

Upgrade tools for CakePHP meant to facilitate migrating from one version of the framework to another
PHP
110
star
16

bake

The Bake Command Plugin
PHP
110
star
17

database

[READ-ONLY] Flexible and powerful Database abstraction library with a familiar PDO-like API. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp
PHP
91
star
18

collection

[READ-ONLY] Collection library in CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp
PHP
88
star
19

elastic-search

Elastic search datasource for CakePHP
PHP
87
star
20

legacy-twig-view

Twig for CakePHP
PHP
81
star
21

authorization

PSR7 Middleware for authorization
PHP
76
star
22

old-cookbook

[Unmaintained] CakePHP Cookbook/Online Manual Repository
JavaScript
59
star
23

core

[READ-ONLY] CakePHP Framework Core Classes. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp
PHP
59
star
24

cakephp-netbeans

CakePHP support in NetBeans
Java
58
star
25

cache

[READ-ONLY] Easy to use Caching library with support for multiple caching backends. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp
PHP
51
star
26

plugins.cakephp.org

Self-contained application that automatically tracks cakephp developer's open source code repositories, including applications and plugins
PHP
50
star
27

cakephp-tmbundle

Official CakePHP TextMate Bundle Git Repository
46
star
28

datasource

[READ-ONLY] Provides connection managing and traits for Entities and Queries that can be reused for different datastores. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp
PHP
46
star
29

codeception

CakePHP module for Codeception
PHP
46
star
30

validation

[READ-ONLY] Validation library from CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp
PHP
43
star
31

queue

A queue-interop compatible Queueing library
PHP
37
star
32

plugin-installer

A composer installer for installing CakePHP plugins.
PHP
32
star
33

i18n

[READ-ONLY] Provides support for message translation and localization for dates and numbers. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp
PHP
29
star
34

cakephp-api-docs

CakePHP API Docs
PHP
29
star
35

log

[READ-ONLY] Logging library with support for multiple different streams. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp
PHP
26
star
36

cms-tutorial

The completed CMS tutorial for CakePHP
PHP
26
star
37

old-bakery

No longer used code for bakery.cakephp.org
PHP
24
star
38

bookmarker-tutorial

The finished result of the bookmarker tutorial. Also serves as a sample application using CakePHP 3.x
PHP
24
star
39

event

[READ-ONLY] The event dispatcher library for CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp
PHP
22
star
40

filesystem

[READ ONLY] Convenience library to help you work with files and folders.
PHP
20
star
41

irc.cakephp.org

Official CakePHP IRC Bot Repository
PHP
14
star
42

twig-view

Twig View for CakePHP
PHP
13
star
43

sphinxtheme

Sphinx theme and common configuration for CakePHP documentation projects.
CSS
12
star
44

cakephp.org

Main CakePHP Site
PHP
11
star
45

search.cakephp.org

An Elastic search wrapper for the CakePHP documentation search.
PHP
9
star
46

inflector.cakephp.org

CakePHP Inflector Website
PHP
9
star
47

form

[READ-ONLY] - Form abstraction used to create forms not tied to ORM backed models, or to other permanent datastores.
PHP
9
star
48

cakephp.github.com

7
star
49

CakeFest-2010-Workshop

CakeFest 2010 Workshop
PHP
7
star
50

console

[Read only] Console libraries from CakePHP
PHP
6
star
51

repl

Console tools for a REPL interface for CakePHP applications
PHP
6
star
52

bin.cakephp.org

CakePHP paste bin
PHP
6
star
53

http

[READONLY] HTTP client and server libraries
PHP
6
star
54

bakery.cakephp.org

The Official CakePHP blog
CSS
5
star
55

docs-builder

A set of common tools to build documentation sites for plugins
PHP
5
star
56

CakeFest-2012-Workshop

CakeFest 2012 Workshop
PHP
5
star
57

cakefest2020

Code and examples for CakeFest 2020 workshops
PHP
4
star
58

tutorials.cakephp.org

PHP
3
star
59

csfnavbar

[Unmaintained] Top bar navigation for CakePHP domains
CSS
3
star
60

.github

3
star
61

discord-slack-bridge

An internal discord <=> slack chat bridge
Dockerfile
2
star
62

cdn.cakephp.org

2
star
63

community.cakephp.org

PHP
2
star
64

cakefest2021

Code examples for CakeFest 2021 Workshops
PHP
2
star
65

site-book

A simple repository containing the necessary config to deploy the api site
Python
2
star
66

api-app

An API focused application skeleton
PHP
2
star
67

docs-theme

Community theme for plugin documentation
CSS
2
star
68

site-api

A simple repository containing the necessary config to deploy the api site
Python
1
star
69

cakefest-2016-workshops

Repo to hold source code used during CakeFest 2016 Workshops
PHP
1
star
70

cakebot

CoffeeScript
1
star
71

code-of-conduct

Contributor Code of Conduct
1
star