This document discusses agile database access with CakePHP 3. It covers types of object-relational mappers (ORMs), setting up associations between tables, performing simple and complex queries, formatting and debugging queries, modifying JSON output, using value objects, and more advanced topics like custom serialization and associations between databases. The goal is to provide an ORM that is quick, flexible, and easy to work with for both simple and complex database needs.
Internationalizing CakePHP ApplicationsPierre MARTIN
Slides from the talk given by Mariano Iglesias during the CakeFest #3 - July 2009
Note: the original pdf and the code related to this talk can be found on cakephp.org (http://cakephp.org/downloads/CakeFest/CakeFest%203%20-%20Berlin%202009/Mariano%20Iglesias%20-%20Internationalizing%20CakePHP%20Applications)
CakePHP 3 comes with a new ORM. This talk starts with a short history of how this library came to be and then walk through a series of examples from beginner to advanced for using the Querying features of the ORM.
This talk is an overview of the history of the PHP language and major framework projects that have emerged in the last 5 years. It examines what we've learned in the development of these frameworks, how that education has been brought to bear in Lithium. Most of this talk ended up being me demoing and answering questions, so there's not a lot of content in the slides, sorry.
Internationalizing CakePHP ApplicationsPierre MARTIN
Slides from the talk given by Mariano Iglesias during the CakeFest #3 - July 2009
Note: the original pdf and the code related to this talk can be found on cakephp.org (http://cakephp.org/downloads/CakeFest/CakeFest%203%20-%20Berlin%202009/Mariano%20Iglesias%20-%20Internationalizing%20CakePHP%20Applications)
CakePHP 3 comes with a new ORM. This talk starts with a short history of how this library came to be and then walk through a series of examples from beginner to advanced for using the Querying features of the ORM.
This talk is an overview of the history of the PHP language and major framework projects that have emerged in the last 5 years. It examines what we've learned in the development of these frameworks, how that education has been brought to bear in Lithium. Most of this talk ended up being me demoing and answering questions, so there's not a lot of content in the slides, sorry.
PHP Data Objects (PDO) provides a clear, simple (but powerful), unified API for working with all our favorite databases. Features include prepared statements with bound parameters (for all databases, even those that don’t natively support them), transactions, cursors, LOBs, and flexible error handling.
Lithium: The Framework for People Who Hate FrameworksNate Abele
This is the presentation was given at ConFoo on March 11th by Nate Abele and Joël Perras, and is an introduction to the architectural problems with other frameworks that Lithium was designed to address, and how it addresses them. It also introduces programming paradigms like functional and aspect-oriented programming which address issues that OOP doesn't account for.
Finally, the talk provides a quick overview of the innovative and unparalleled features that Lithium provides, including the data layer, which supports both relational and non-relational databases.
PHP 5.3 and Lithium: the most rad php frameworkG Woo
Presentation given to the Orange County PHP meetup on Feb 24 2010. The presentation covers the new features in php 5.3 and goes on to show how they are used in Lithium, the most rad php framework.
Building Lithium Apps (Like a Boss) was a workshop presented on the structure and philosophy of the Lithium framework and its applications, and how best to take advantage of them.
How do you measure the quality of your code? Performance and testing are just one aspect of code, in order to meet deadlines and make maintenance quicker you also need your code to be readable, decoupled and generally easier to comprehend and work with. This talk will go over tips and exercises to help you identify trouble areas, refactor them and train you to write better code in future projects. Come make your code look and function better.
A lot of people using PHPunit for testing their source code. While I was observing my team I recognized most of them are only using the standard assertions like 'assertEquals()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis and it digs deep into uncommon features of PHPUnit.
PHP Data Objects (PDO) provides a clear, simple (but powerful), unified API for working with all our favorite databases. Features include prepared statements with bound parameters (for all databases, even those that don’t natively support them), transactions, cursors, LOBs, and flexible error handling.
Lithium: The Framework for People Who Hate FrameworksNate Abele
This is the presentation was given at ConFoo on March 11th by Nate Abele and Joël Perras, and is an introduction to the architectural problems with other frameworks that Lithium was designed to address, and how it addresses them. It also introduces programming paradigms like functional and aspect-oriented programming which address issues that OOP doesn't account for.
Finally, the talk provides a quick overview of the innovative and unparalleled features that Lithium provides, including the data layer, which supports both relational and non-relational databases.
PHP 5.3 and Lithium: the most rad php frameworkG Woo
Presentation given to the Orange County PHP meetup on Feb 24 2010. The presentation covers the new features in php 5.3 and goes on to show how they are used in Lithium, the most rad php framework.
Building Lithium Apps (Like a Boss) was a workshop presented on the structure and philosophy of the Lithium framework and its applications, and how best to take advantage of them.
How do you measure the quality of your code? Performance and testing are just one aspect of code, in order to meet deadlines and make maintenance quicker you also need your code to be readable, decoupled and generally easier to comprehend and work with. This talk will go over tips and exercises to help you identify trouble areas, refactor them and train you to write better code in future projects. Come make your code look and function better.
A lot of people using PHPunit for testing their source code. While I was observing my team I recognized most of them are only using the standard assertions like 'assertEquals()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis and it digs deep into uncommon features of PHPUnit.
Cake PHP Mamba Plugin is User Management Plugin for Cake PHP. It has 16 features. It allows User Registration, Login, Add/Edit/Delete User by Admin, Add/Edit/Delete Group by Admin and many more features.
Check the demo at http://www.mamba.getyourplugin.com
Segurança de APIs HTTP, um guia sensato para desenvolvedores preocupadosLuis Cipriani
Liberar uma API HTTP para seus usuários é a melhor forma de estimular ideias inovadoras baseadas no seu produto, porém para ser livre é necessário responsabilidade. Você já pensou qual o melhor método para garantir a segurança dos dados de seus usuários? Será que só basta implementar o melhor método de autenticação do mercado? Como balancear segurança com a queda de performance percebida pelo usuário, devido ao overhead do processo de autenticação? Devo me preocupar com rate-limiting?
Com foco nesses desafios, a palestra apresentará os métodos de autenticação de APIs, suas vantagens e desvantagens, quando utilizar cada uma e liberar os dados com cabeça tranquila.
Can't Miss Features of PHP 5.3 and 5.4Jeff Carouth
If you're like me you remember the days of PHP3 and PHP4; you remember when PHP5 was released, and how it was touted to change to your life. It's still changing and there are some features of PHP 5.3 and new ones coming with PHP 5.4 that will improve your code readability and reusability. Let's look at some touted features such as closures, namespaces, and traits, as well as some features being discussed for future releases.
In 2010, I told everyone how to start unit testing Zend Framework applications. In 2011, let’s take this a step further by testing services, work flows and performance. Looking to raise the bar on quality? Let this talk be the push you need to improve your Zend Framework projects.
https://speakerdeck.com/willroth/50-laravel-tricks-in-50-minutes - origin
Laravel 5.1 raised the bar for framework documentation, but there's much, much more lurking beneath the surface. In this 50-minute session, we'll explore 50 (yes, 50!) high-leverage implementation tips & tricks that you just won't find in the docs: the IoC Container, Blade, Eloquent, Middleware, Routing, Commands, Queues, Events, Caching — we'll cover them all! Join us as we drink from the fire hose & learn to take advantage of everything that Laravel has to offer to build better software faster!
You’ve built a WordPress site or two (or 10), your installed plugins and themes to MOSTLY get what you want. Now you’re ready to learn the inner workings of WordPress and take your development to the next level. Jump into WordPress development and PHP by building a Plugin and learn to speak WordPress’ language: PHP.
n 2010, I told everyone how to start unit testing Zend Framework applications. In 2011, let’s take this a step further by testing services, work flows and performance. Looking to raise the bar on quality? Let this talk be the push you need to improve your Zend Framework projects.
Your code sucks, let's fix it - DPC UnConRafael Dohms
How do you measure the quality of your code? Performance and testing are just one aspect of code, in order to meet deadlines and make maintenance quicker you also need your code to be readable, decoupled and generally easier to comprehend and work with. This talk will go over tips and exercises to help you identify trouble areas, refactor them and train you to write better code in future projects. Come make your code look and function better.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
2. Agenda
1. Types of ORMs
2. What I need from ORMs
3. What is agile for me?
4. A simple setup
5. Simple analytical queries
6. More complex examples
7. Query composition and collections
8. Formatting results
9. A last minute tip
10. Debugging Queries
11. Working with JSON
12. Value objects
1
8. 7
What I need from an ORM
To stop me from repeating the same over and over.
Help me modularize my common searches.
Stay out of the way when I want to create complex stuff.
Testability.
Ways to hook in and change any default behavior.
To not hide the Relational aspect of a Relational database.
9. 8
What is Agile?
Quick feedback loop.
Low friction,
Easy to debug.
Easy to track.
Few requirements.
Ability to scale up.
10. 9
The Setup
class ManagersTable extends Table
{
public function initialize(array $config = [])
{
$this->table('departments_managers');
$this->primaryKey(['department_id', 'employee_id']);
$this->belongsTo('Employees', ['joinType' => 'INNER']);
$this->belongsTo('Departments', ['joinType' => 'INNER']);
}
public function beforeFind($event, $query, $options)
{
$query->andWhere(['to_date IS' => NULL]);
}
}
11. 10
The Setup
class EmployeesTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->hasMany('Salaries');
$this->hasMany('Titles');
$this->belongsToMany('Departments');
}
}
12. 11
Simple analytical queries
Average historic salary
// In SalariesTable.php
public function findAverage(Query $query, $options = [])
{
return $query->select(['average' => $query->func()->avg('Salaries.salary')]);
}
{
"average": 63810.74
}
13. 12
Simple analytical queries
Currently hired female managers
public function findFemale(Query $query, $options = [])
{
return $query->contain(['Employees'])->where(['Employees.gender' => 'F']);
}
SELECT Managers.*, Employees.*
FROM department_managers Managers
INNER JOIN employees Employees ON Employees.id = (Managers.employee_id)
WHERE Employees.gender = 'F' AND to_date IS NULL
14. 13
A more complex example
Percentage of currently hired female
managers
public function findFemaleRatio(Query $query, $options = [])
{
$allManagers = $this->find()->select($query->func()->count('*'));
$ratio = $query
->newExpr($query->func()->count('*'))
->type('/')
->add($allManagers)
return $query
->find('female')
->select(['female_ratio' => $ratio]);
}
{
"female_ratio": 0.4444
}
15. 14
Queries can be composed
Average salary of currently hired
employees by gender
public function findOfHired(Query $query, $options = [])
{
return $query->contain(['Employees'])->where(['Salaries.to_date IS' => null]);
}
public function findAveragePerGender(Query $query, $options = [])
{
return $query
->select(['gender' => 'Employees.gender'])
->find('average')
->contain(['Employees'])
->group(['Employees.gender']);
}
$salariesTable
->find('ofHired')
->find('averagePerGender')
->indexBy('gender');
16. 15
Queries are Collections
Yearly salary average per department and
gender
public function findAveragePerDepartment(Query $query, $options = [])
{
return $query
->select(['department' => 'Departments.name'])
->find('average')
->matching('Employees.Departments')
->where([
'Salaries.from_date < DepartmentsEmployees.to_date',
'Salaries.from_date >= DepartmentsEmployees.from_date',
])
->group(['Departments.id']);
}
17. 16
Queries are Collections
Yearly salary average per department and
gender
public function findAveragePerYear(Query $query, $options = [])
{
$year = $query->func()->year(['Salaries.from_date' => 'literal']);
return $query
->select(['year' => $year])
->find('average')
->group([$year]);
}
$averages = $salariesTable
->find('averagePerYear')
->find('averagePerDepartment')
->find('averagePerGender');
18. 17
Queries are Collections
Yearly salary average per department and
gender
$averages->groupBy('year')->each(function ($averages, $year) {
displayYear($year);
collection($averages)->groupBy('department')->each(function ($d, $averages) {
displayDepartment($d);
collection($averages)->each('displayAverage');
})
});
19. 18
Result Formatters
Pack common post-processing into
custom finders
public function findGroupedByYearAndDepartment($query)
{
return $query->formatResults(function ($results) {
return $results->groupBy('year');
})
->formatResults(function ($years) {
return $years->map(function ($results) {
return collection($results)->groupBy('department');
});
});
}
$salariesTable
->find('averagePerYear')
->find('averagePerDepartment')
->find('averagePerGender')
->find('groupedByYearAndDepartment');
20. 19
Result Formatters
They look sexier in HackLang
public function findGroupedByYearAndDepartment($query)
{
return $query
->formatResults($results ==> $results->groupBy('year'))
->formatResults($years ==> $years->map(
$results ==> collection($results)->groupBy('department')
);
}
21. 20
Associations in another
database
Use tables from other databases by
specifying the strategy
public function initialize(array $config)
{
$this->hasOne('LinkedEmployee', [
'className' => 'ExternalSystemEmployeesTable',
'strategy' => 'select'
]);
}
A gotcha: It will not be possible to use matching()
22. 21
Debugging Queries
debug($query) Shows the SQL and bound params, does not show results
debug($query->all()) Shows the ResultSet properties (not the results)
debug($query->toArray()) An easy way to show each of the results
debug(json_encode($query, JSON_PRETTY_PRINT)) More human readable results.
debug($query->first()) Show the properties of a single entity.
debug((string)$query->first()) Show the properties of a single entity as JSON.
23. 22
Debugging Queries
Pro tip: create a dj() function
function dj($data)
{
debug(json_encode($data, JSON_PRETTY_PRINT), null, false);
}
dj($query);
[
{
"average": 0.4444
}
]
24. 23
Modifying JSON output
I don't want to show primary keys or
foreign keys
class Employee extends Entity
{
protected $_hidden = [
'id'
];
}
class Manager extends Entity
{
protected $_hidden = [
'employee_id',
'department_id'
];
}
25. 24
Modifying JSON output
I want to show employees' full name
class Employee extends Entity
{
protected $_virtual = [
'full_name'
];
protected function _getFullName()
{
return $this->name . ' ' . $this->last_name;
}
}
26. 25
Custom serialization
Let's try to do HAL
public function index()
{
$managers = $this->paginate($this->Managers);
$managers = $managers->map(new LinksEnricher($this->Managers));
$this->set('managers', $managers);
$this->set('_serialize', ['managers']);
}
27. 26
Custom Serialization
Let's try to do HAL
class LinksEnricher
{
...
public function __invoke(EntityInterface $row)
{
$primaryKey = array_values($row->extract((array)$this->table->primaryKey()));
$row->_links = [
'self' => [
'href' => Router::url([
'controller' => $row->source(),
'action' => 'view',
] + $primaryKey)
],
];
return $this->enrich($row); // Recurse for associations
}
...
}
29. }
28
Value Objects
Why?
Allow to add custom logic to dumb data.
Help with custom serialization
Make translation and localization easier
Auto-validation
Greater integrity.
30. 29
Value Objects
Adding logic to plain data
class Gender implements JsonSerializable
{
private static $genders = [];
protected $short;
protected $name;
protected function __construct($gender)
{
$this->short = $gender;
$this->name = $gender === 'F' ? 'Female' : 'Male';
}
public static function get($gender)
{
...
return $genders[$gender] = new static($gender);
}
...
31. 30
Value Objects
Accepting value objects
class Employee extends Entity
{
protected function _setGender($gender)
{
return Gender::get($gender);
}
$employeeEntity->gender = 'F';
get_class($employeeEntity->gender); // AppModelValueGender
$employeeEntity->gender = Gender::get('F');
32. 31
Value Objects
Wiring them to the database
class GenderType extends Type
{
...
}
Type::build('gender', 'AppModelDatabaseType');
class EmployeesTable extends Table
{
...
protected function _initializeSchema(Schema $schema)
{
$schema->columnType('gender', 'gender');
return $schema;
}
}
33. 32
Value Objects
Using them in Queries
$employee->gender = Gender::get('F');
$result = $employeesTable->find()->where([['gender' => $employee->gender]])->first();
$employee->gender === $result->gender;
You can use objects as values in where conditions (or any query expression)
34. 33
Thanks for your time
Questions?
https://github.com/lorenzo/cakephp3-advanced-examples