SlideShare uma empresa Scribd logo
1 de 33
CakeEntity
The ActiveRecord
     for CakePHP
        Basuke Suzuki @basuke
  https://github.com/kanshin/CakeEntity
me

• Basuke Suzuki @basuke
• Mac / iPhone / Newton
• PHP : 10+ years
What is CakeEntity?
•   Plugin for CakePHP
•   Support ActiveRecord in Model
•   100% compatible with the standard Model.
•   Open source. Available in GitHub
•   https://github.com/kanshin/CakeEntity
•   CakePHP 1.3, PHP 5.2 >
Active Record

ActiveRecord is "an object that wraps a row in a

database table or view, encapsulates database

access and adds domain logic on that data".

                                     Fowler, 2003
         http://www.martinfowler.com/books.html
Cons.

 find() returns array of object.
 You can manipulate object immediately, directly.

$post = $this->Post->entity(); // creation
$post->content = "Hello world!";
$post->save();
Cons. cont.

• Less array() and [ brankets ].
• Makes code structure simple.
  • Safe access to domain logic from View.
  • More code moves from Helper to Model.
  • More code moves from Controller to Model.
• Testable.
Prepare
first things first

Place in the plugins directory.
Name should be “Entity”.

app/plugins/entity/
   or
plugins/entity/
Extends EntityModel

App::import('Model', 'Entity.EntityModel');
class Post extends EntityModel {
   ...
}
Find
'entity' => true

$this->Post->find('all', array(
      'conditions' => ...
      'order' => ...
      'entity' => true,
));
Result is array of
         object
                                                    ������������

$result = [
   {id: 1, title:"title1", author_id:"123", ... }
   {id: 2, title:"title2", content:"...", }
   ...
];

// works fine with paginate()
Works with
           “belongsTo”
// Post -> belongsTo -> Author
$this->Post->find('all', array(
      'conditions' => ...
      'contain' => array('Author'),
      'entity' => true,
));
Property is also Entity

 $result = [
     {title:"title1", author: {id:3,
     name:"Basuke"}, ... }
     {title:"title2", author:null, ... }
     ...
 ];
 // property name is converted to lower case
Of course, works with
     “hasMany”
// Post -> hasMany -> Image
$this->Post->find('all', array(
      'conditions' => ...
      'contain' => array('Image'),
      'entity' => true,
));
Property holds array
     of Entity
$result = [
    {title:"title1", images: [ {path:"..."},
    {path:"..."}] }
    {title:"title2", images: [{path:"..."}, ...] }
    ...
];
// property name is pluralized.
load
Fetch one entity
$post = $this->Post->find('first', array(
       'conditions' => array('id'=>$id),
       'entity' => true,
));
      or
$post = $this->Post->entityById($id);
instantiation.
Instantiation is easy

  $post = $this->Post->entity();
  $post->title = “Hello”;

• Don’t use “new”. PostEntity class has no
  information of model.
  $post = new PostEntity();
Save
Save is easy.

$post->title = "Hello world";
$post->content = file_get_content(...);
if ($post->save()) {
    $this->isCool();
}
Entity Class

Entity Class is a default class when EntityModel
will instantiate object.
Customizable with sub class of Entity.
Many features to works with View layer.
The result of method call can be cached.
Property access can be restricted.
Entity Subclass
If class with model’s name + “Entity” is exists, that
class is used instead.

class PostEntity extends Entity {

 ...
}

Or override entityClass().
Custom subclass
  depending by data
protected function entityClassForData($data) {

 switch ($data[‘type’]) {

 
 case ‘hyper’:

 
 
 return ‘HyperPostEntity’;

 
 default:

 
 
 return ‘PlainPostEntity’;

 }
}
Domain logic can be
placed in Entity subclass

 Object is the place of domain logic.

 Method for collection should be placed in Model.
 Method for record should be placed in Entity.
   ex) isHidden(), publish() is the candidates.
Easy access for
 property and method
• For $post->property_name
  • $post[‘property_name’] is OK
• For $post->some_method()
  • $post[‘some_method’] is also OK
• Array access is cacheable.

• Wait! I want to increase [ ] any more! Why?
{Smarty} uses “.”


• Smarty uses dot to access array.
  • i.e {$post.property_name}
• Also reduce ( ) for method access.
• Easier code reading.
Method access control
  
 public function allows() {
  
 
 return array();
  
 }

• Override allows(). Return name of method to
  allow access.

• Or define public method.
Result is cached
          automatically
    public $comments;
    public function comments() {
    
 $Comment = $this->getModel()->Comment;
    
 return $Comment->find(array(
    
 
 ...
    
 ));
    }

•   $post[‘comments’] is cached.
Future

CakePHP 2.0, of course.
Reverse conversion to array structure.
More tests.
saveAll() support.
dirty property detection.
Document is


not ready. Sorry.
Sample is available soon.
Thanks




http://d.hatena.ne.jp/basuke/

Mais conteúdo relacionado

Mais procurados

Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway ichikaway
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkG Woo
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Fabien Potencier
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionNate Abele
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax pluginsInbal Geffen
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Fabien Potencier
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Fabien Potencier
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreNicolas Carlo
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionRifat Nabi
 

Mais procurados (20)

Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Mysql & Php
Mysql & PhpMysql & Php
Mysql & Php
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 

Destaque

初めての単体テスト
初めての単体テスト初めての単体テスト
初めての単体テストBasuke Suzuki
 
iOS4時代の位置情報サービスの使い方
iOS4時代の位置情報サービスの使い方iOS4時代の位置情報サービスの使い方
iOS4時代の位置情報サービスの使い方Basuke Suzuki
 
PostgreSQLからMongoDBへ
PostgreSQLからMongoDBへPostgreSQLからMongoDBへ
PostgreSQLからMongoDBへBasuke Suzuki
 
Vue.js 2.0を試してみた
Vue.js 2.0を試してみたVue.js 2.0を試してみた
Vue.js 2.0を試してみたToshiro Shimizu
 

Destaque (6)

CoAP Talk
CoAP TalkCoAP Talk
CoAP Talk
 
初めての単体テスト
初めての単体テスト初めての単体テスト
初めての単体テスト
 
iOS4時代の位置情報サービスの使い方
iOS4時代の位置情報サービスの使い方iOS4時代の位置情報サービスの使い方
iOS4時代の位置情報サービスの使い方
 
PostgreSQLからMongoDBへ
PostgreSQLからMongoDBへPostgreSQLからMongoDBへ
PostgreSQLからMongoDBへ
 
Vue.js 2.0を試してみた
Vue.js 2.0を試してみたVue.js 2.0を試してみた
Vue.js 2.0を試してみた
 
Vue.js入門
Vue.js入門Vue.js入門
Vue.js入門
 

Semelhante a CakeEntity: ActiveRecord for CakePHP

PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
Php on the desktop and php gtk2
Php on the desktop and php gtk2Php on the desktop and php gtk2
Php on the desktop and php gtk2Elizabeth Smith
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmdiKlaus
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patternsSamuel ROZE
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
Legacy applications - 4Developes konferencja, Piotr Pasich
Legacy applications  - 4Developes konferencja, Piotr PasichLegacy applications  - 4Developes konferencja, Piotr Pasich
Legacy applications - 4Developes konferencja, Piotr PasichPiotr Pasich
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 
DRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEWDRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEWDrupalCamp Kyiv
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectJonathan Wage
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteLeonardo Proietti
 

Semelhante a CakeEntity: ActiveRecord for CakePHP (20)

PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Php on the desktop and php gtk2
Php on the desktop and php gtk2Php on the desktop and php gtk2
Php on the desktop and php gtk2
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
 
Oops in php
Oops in phpOops in php
Oops in php
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
php2.pptx
php2.pptxphp2.pptx
php2.pptx
 
Legacy applications - 4Developes konferencja, Piotr Pasich
Legacy applications  - 4Developes konferencja, Piotr PasichLegacy applications  - 4Developes konferencja, Piotr Pasich
Legacy applications - 4Developes konferencja, Piotr Pasich
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
DRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEWDRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEW
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Último (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

CakeEntity: ActiveRecord for CakePHP

  • 1. CakeEntity The ActiveRecord for CakePHP Basuke Suzuki @basuke https://github.com/kanshin/CakeEntity
  • 2. me • Basuke Suzuki @basuke • Mac / iPhone / Newton • PHP : 10+ years
  • 3. What is CakeEntity? • Plugin for CakePHP • Support ActiveRecord in Model • 100% compatible with the standard Model. • Open source. Available in GitHub • https://github.com/kanshin/CakeEntity • CakePHP 1.3, PHP 5.2 >
  • 4. Active Record ActiveRecord is "an object that wraps a row in a database table or view, encapsulates database access and adds domain logic on that data". Fowler, 2003 http://www.martinfowler.com/books.html
  • 5. Cons. find() returns array of object. You can manipulate object immediately, directly. $post = $this->Post->entity(); // creation $post->content = "Hello world!"; $post->save();
  • 6. Cons. cont. • Less array() and [ brankets ]. • Makes code structure simple. • Safe access to domain logic from View. • More code moves from Helper to Model. • More code moves from Controller to Model. • Testable.
  • 8. first things first Place in the plugins directory. Name should be “Entity”. app/plugins/entity/ or plugins/entity/
  • 10. Find
  • 11. 'entity' => true $this->Post->find('all', array( 'conditions' => ... 'order' => ... 'entity' => true, ));
  • 12. Result is array of object ������������ $result = [ {id: 1, title:"title1", author_id:"123", ... } {id: 2, title:"title2", content:"...", } ... ]; // works fine with paginate()
  • 13. Works with “belongsTo” // Post -> belongsTo -> Author $this->Post->find('all', array( 'conditions' => ... 'contain' => array('Author'), 'entity' => true, ));
  • 14. Property is also Entity $result = [ {title:"title1", author: {id:3, name:"Basuke"}, ... } {title:"title2", author:null, ... } ... ]; // property name is converted to lower case
  • 15. Of course, works with “hasMany” // Post -> hasMany -> Image $this->Post->find('all', array( 'conditions' => ... 'contain' => array('Image'), 'entity' => true, ));
  • 16. Property holds array of Entity $result = [ {title:"title1", images: [ {path:"..."}, {path:"..."}] } {title:"title2", images: [{path:"..."}, ...] } ... ]; // property name is pluralized.
  • 17. load
  • 18. Fetch one entity $post = $this->Post->find('first', array( 'conditions' => array('id'=>$id), 'entity' => true, )); or $post = $this->Post->entityById($id);
  • 20. Instantiation is easy $post = $this->Post->entity(); $post->title = “Hello”; • Don’t use “new”. PostEntity class has no information of model. $post = new PostEntity();
  • 21. Save
  • 22. Save is easy. $post->title = "Hello world"; $post->content = file_get_content(...); if ($post->save()) { $this->isCool(); }
  • 23. Entity Class Entity Class is a default class when EntityModel will instantiate object. Customizable with sub class of Entity. Many features to works with View layer. The result of method call can be cached. Property access can be restricted.
  • 24. Entity Subclass If class with model’s name + “Entity” is exists, that class is used instead. class PostEntity extends Entity { ... } Or override entityClass().
  • 25. Custom subclass depending by data protected function entityClassForData($data) { switch ($data[‘type’]) { case ‘hyper’: return ‘HyperPostEntity’; default: return ‘PlainPostEntity’; } }
  • 26. Domain logic can be placed in Entity subclass Object is the place of domain logic. Method for collection should be placed in Model. Method for record should be placed in Entity. ex) isHidden(), publish() is the candidates.
  • 27. Easy access for property and method • For $post->property_name • $post[‘property_name’] is OK • For $post->some_method() • $post[‘some_method’] is also OK • Array access is cacheable. • Wait! I want to increase [ ] any more! Why?
  • 28. {Smarty} uses “.” • Smarty uses dot to access array. • i.e {$post.property_name} • Also reduce ( ) for method access. • Easier code reading.
  • 29. Method access control public function allows() { return array(); } • Override allows(). Return name of method to allow access. • Or define public method.
  • 30. Result is cached automatically public $comments; public function comments() { $Comment = $this->getModel()->Comment; return $Comment->find(array( ... )); } • $post[‘comments’] is cached.
  • 31. Future CakePHP 2.0, of course. Reverse conversion to array structure. More tests. saveAll() support. dirty property detection.
  • 32. Document is not ready. Sorry. Sample is available soon.

Notas do Editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n