This document provides information about a CakePHP workshop including the presenter, development environment setup instructions, and an overview of the workshop content. Some key points:
- The presenter is Walther Lalk, a CakePHP core team member.
- Instructions are provided for setting up a development environment using Vagrant or the built-in PHP server.
- The workshop will cover installing CakePHP, baking a database and entities, authentication, authorization, and using CRUD to generate basic CRUD functionality.
- Attendees will build an events application with members, events, and event attendance tracking. Security, validation, and associations between entities will be implemented.
- CRUD will be
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
As presented at ZendCon 2014, AmsterdamPHP, PHPBenelux 2014, Sweetlake PHP and PHP Northwest 2013, an overview of some different patterns for integrating and managing logic throughout your application.
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.
As presented at Dutch PHP Conference 2015, an introduction to command buses, how to implement your own in PHP and why they're both useful but unimportant.
Silex is a brand new PHP 5.3 micro framework built on top of the Symfony2 de decoupled components. In this session, we will discover how to build and deploy powerful REST web services with such a micro framework and its embedded tools.
The first part of this talk will introduce the basics of the REST architecture. We fill focus on the main concepts of REST like HTTP methods, URIs and open formats like XML and JSON.
Then, we will discover how to deploy REST services using most of interesting Silex tools like database abstraction layer, template engine and input validation. We will also look at unit and functional testing frameworks with PHPUnit and HTTP caching with Edge Side Includes and Varnish support to improve performances.
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
As presented at ZendCon 2014, AmsterdamPHP, PHPBenelux 2014, Sweetlake PHP and PHP Northwest 2013, an overview of some different patterns for integrating and managing logic throughout your application.
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.
As presented at Dutch PHP Conference 2015, an introduction to command buses, how to implement your own in PHP and why they're both useful but unimportant.
Silex is a brand new PHP 5.3 micro framework built on top of the Symfony2 de decoupled components. In this session, we will discover how to build and deploy powerful REST web services with such a micro framework and its embedded tools.
The first part of this talk will introduce the basics of the REST architecture. We fill focus on the main concepts of REST like HTTP methods, URIs and open formats like XML and JSON.
Then, we will discover how to deploy REST services using most of interesting Silex tools like database abstraction layer, template engine and input validation. We will also look at unit and functional testing frameworks with PHPUnit and HTTP caching with Edge Side Includes and Varnish support to improve performances.
A long time ago in code base not so far away...
It's a time of prosperity and happiness. Development Teams have improved their coding skills and are now very familiar with writing code with proper DocBlock comments and unit tests, safeguarding their code bases against unwanted behaviour. But the evil Internet is building their new weapon against the Development Teams and sneaks through the gaps still uncovered by tests.
Will the Development Teams be in time to safeguard their code base again and bring peace and balance in the universe?
This session introduces most well known design patterns to build PHP classes and objects that need to store and fetch data from a relational databases. The session will describe the difference between of the Active Record, the Table and Row Data Gateway and the Data Mapper pattern. We will also examine some technical advantages and drawbacks of these implementations. This talk will expose some of the best PHP tools, which ease database interactions and are built on top of these patterns.
Persistence is one of the most important part in a PHP project. Persisting data to a database came with PHP/FI and its MySQL support. From native extensions and PHP4 database abstraction libraries to PDO and modern ORM frameworks, you will (re)discover how persistence has evolved during the last decade. This talk will also introduce the future of data persistence with the growing success of alternative storage engines.
With over 3400 available built-in function, PHP offers a tremendously rich environment. Yet, some of these functions are still unknown to most programmers. During this session, Damien Seguy will highlight a number of functions that are rarely used in PHP, but are nonetheless useful and available within standard distributions.
Closing keynote, as presented at Codemotion 2014, LaraconEU 2014, Redevelop 2014, CodeConnexx 2013 and PHP North East 2014.
This presentation makes a reference to a reading list I received. For those interested, the release consists of most of the general classics, such as Gang Of Four "Design Patterns", The Pragmatic Programmer, Structure and Interpretation of Computer Programs, Domain Driven Design and a few others. The actual list remains tucked away in a box somewhere.
How do you create applications with an incredible level of extendability without losing readability in the process? What if there's a way to separate concerns not only on the code, but on the service definition level? This talk will explore structural and behavioural patterns and ways to enrich them through tricks of powerful dependency injection containers such as Symfony2 DIC component.
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
Cette conférence présente deux grands motifs de conception : l'observateur et l'injection de dépendance. Ce sujet allie à la fois théorie et pratique. Le composant autonome EventDispatcher de Symfony ainsi que le conteneur d'injection de dépendance Pimple sont mis à l'honneur avec des exemples pratiques d'usage. Ces cas pratiques combinent du code de l'ORM Propel ainsi que le composant autonome Zend\Search\Lucene du Zend Framework 2
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.
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. Making right decision about these investments is very tricky and the cost of wrong decisions might be crippling for both business and teams that support it.
Extreme Programming and Test Driven Development in particular are practices that are aiming at supporting development effort by making it easier to introduce change. That said, sometimes those tools can become a problem of its own when applied in the wrong way or for the wrong context. Understanding software cost forces is a very important skill of successful teams and something that helps understand how to apply XP and TDD in different contexts.
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonfRafael Dohms
As developers we write code everyday, only to frown at it a week after that. Why do we have such a hard time with code written by others and ourselves, this raging desire to rewrite everything we see? Writing code that survives the test of time and self judgment is a matter of clarity and simplicity. Let's talk about growing, learning and improving our code with calisthenics, readability and good design.
Performance and testing are just one aspect of code, to really be successful your code needs to be readable, maintainable and generally easier to comprehend and work with. This talk draws from my own experience in applying the techniques of object calisthenics and code readability, within an existing team. It will help you identify trouble areas, learn how to refactor them and train you to write better code in future projects avoiding common pitfalls.
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
Slides from my talk presented during Dutch PHP Conference in Amsterdam - 25 June 2016
More Domain-Driven Design related content at: https://domaincentric.net/
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.
This guy found these 2 grizzly cubs with the dead mother in Alaska . One cub survived and he managed to raise it to maturity.
You can see how his family interacted with the bear as it matured. Look at the size he has grown to. The bear must feel he's another pet (notice the honored guest at Thanksgiving dinner) and the humans are his "family".
He's housebroken, very gentle and comes and goes as he desires. Can you imagine having something like this as a pet? You certainly wouldn't have to worry about someone breaking into your house if you happened to be gone for a few days would you?
A long time ago in code base not so far away...
It's a time of prosperity and happiness. Development Teams have improved their coding skills and are now very familiar with writing code with proper DocBlock comments and unit tests, safeguarding their code bases against unwanted behaviour. But the evil Internet is building their new weapon against the Development Teams and sneaks through the gaps still uncovered by tests.
Will the Development Teams be in time to safeguard their code base again and bring peace and balance in the universe?
This session introduces most well known design patterns to build PHP classes and objects that need to store and fetch data from a relational databases. The session will describe the difference between of the Active Record, the Table and Row Data Gateway and the Data Mapper pattern. We will also examine some technical advantages and drawbacks of these implementations. This talk will expose some of the best PHP tools, which ease database interactions and are built on top of these patterns.
Persistence is one of the most important part in a PHP project. Persisting data to a database came with PHP/FI and its MySQL support. From native extensions and PHP4 database abstraction libraries to PDO and modern ORM frameworks, you will (re)discover how persistence has evolved during the last decade. This talk will also introduce the future of data persistence with the growing success of alternative storage engines.
With over 3400 available built-in function, PHP offers a tremendously rich environment. Yet, some of these functions are still unknown to most programmers. During this session, Damien Seguy will highlight a number of functions that are rarely used in PHP, but are nonetheless useful and available within standard distributions.
Closing keynote, as presented at Codemotion 2014, LaraconEU 2014, Redevelop 2014, CodeConnexx 2013 and PHP North East 2014.
This presentation makes a reference to a reading list I received. For those interested, the release consists of most of the general classics, such as Gang Of Four "Design Patterns", The Pragmatic Programmer, Structure and Interpretation of Computer Programs, Domain Driven Design and a few others. The actual list remains tucked away in a box somewhere.
How do you create applications with an incredible level of extendability without losing readability in the process? What if there's a way to separate concerns not only on the code, but on the service definition level? This talk will explore structural and behavioural patterns and ways to enrich them through tricks of powerful dependency injection containers such as Symfony2 DIC component.
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
Cette conférence présente deux grands motifs de conception : l'observateur et l'injection de dépendance. Ce sujet allie à la fois théorie et pratique. Le composant autonome EventDispatcher de Symfony ainsi que le conteneur d'injection de dépendance Pimple sont mis à l'honneur avec des exemples pratiques d'usage. Ces cas pratiques combinent du code de l'ORM Propel ainsi que le composant autonome Zend\Search\Lucene du Zend Framework 2
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.
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. Making right decision about these investments is very tricky and the cost of wrong decisions might be crippling for both business and teams that support it.
Extreme Programming and Test Driven Development in particular are practices that are aiming at supporting development effort by making it easier to introduce change. That said, sometimes those tools can become a problem of its own when applied in the wrong way or for the wrong context. Understanding software cost forces is a very important skill of successful teams and something that helps understand how to apply XP and TDD in different contexts.
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonfRafael Dohms
As developers we write code everyday, only to frown at it a week after that. Why do we have such a hard time with code written by others and ourselves, this raging desire to rewrite everything we see? Writing code that survives the test of time and self judgment is a matter of clarity and simplicity. Let's talk about growing, learning and improving our code with calisthenics, readability and good design.
Performance and testing are just one aspect of code, to really be successful your code needs to be readable, maintainable and generally easier to comprehend and work with. This talk draws from my own experience in applying the techniques of object calisthenics and code readability, within an existing team. It will help you identify trouble areas, learn how to refactor them and train you to write better code in future projects avoiding common pitfalls.
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
Slides from my talk presented during Dutch PHP Conference in Amsterdam - 25 June 2016
More Domain-Driven Design related content at: https://domaincentric.net/
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.
This guy found these 2 grizzly cubs with the dead mother in Alaska . One cub survived and he managed to raise it to maturity.
You can see how his family interacted with the bear as it matured. Look at the size he has grown to. The bear must feel he's another pet (notice the honored guest at Thanksgiving dinner) and the humans are his "family".
He's housebroken, very gentle and comes and goes as he desires. Can you imagine having something like this as a pet? You certainly wouldn't have to worry about someone breaking into your house if you happened to be gone for a few days would you?
Константин Карпалов — «Cash rules everything around me, или как заработать ми...shevchuk_conf
1. Кратко о рынке микрозаймов: доля СРА в общем объёме лидов на каждом рынке.
2. Способы генерации лидов для Payday Loans.
3. Сколько зарабатывают топовые вебмастера в Payday loans на рынке Польши, Америки, Украины, России.
4. Что любит рекламодатель - варианты увеличения стоимости конверсии.
5. Как не попасть в черный список рекламодателей. Варианты жульничества и способы защиты от них.
6. Как работать напрямую с рекламодателем и зарабатывать на 25% больше.
7. Путь к миллиону - чек лист подходов, при помощи которых вебмастер может значительно улучшить своё финансовое положение.
This presentation is about the devaluation of Indian currency with all major concepts and issues regarding devaluation discussed in it. Basically, Devaluation refers to a reduction in the external value of a currency in terms of other currencies. Here we are particularly talking about the Devaluation of Indian Currency (Rupee) against Foreign Currency(Dollar). Refer to the slides for further details.
Was jeder Java-Entwickler über Strings wissen sollteberndmueller
Strings sind wahrscheinlich der am meisten verwendete Datentyp in jeder
Java-Anwendung. Es ist daher nicht überraschend, dass JDK-Ingenieure
versuchen, Strings möglichst gut zu optimieren oder Bücher über
Performanz-Tuning und Testen dem Thema Strings ganze Kapitel widmen.
Jeder Entwickler sollte daher wissen, was Strings sind und wie sie
sinnvoll und effizient eingesetzt werden können.
Dieser Vortrag stellt JDK-Klassen vor, die mit und auf Strings
arbeiten, sowohl auf der API- aber auch auf der
Implementierungsebene. Wir beleuchten internte Strings und die für sie
verwendeten Speicherbereiche, sowie die noch recht unbekannte
"String-Deduplication"-Option des G1-Garbage-Collectors.
Mit Java 9 ändert sich die interne Repräsentation von Strings.
Wir skizzieren diese Änderungen, die nach außen unsichtbar
bleiben.
WordPress currently powers over 1/5th of the internet and is growing. Historically, people think of WordPress as a blogging platform or use it as a CMS, but can this tool known and used by millions of people also be used to create complex applications? WordPress is familiar, easy to use, actively developed and supported, and has a powerful codebase that allows one to quickly develop applications and websites. These things make WordPress a great option to develop you next application. We will walk through examples of WordPress's use to create applications and very complex sites and then dive into the internals of WordPress that make this happen including: Custom Data Types, WordPress Hooks, Database Interactions, Connecting to Remote APIs, The WordPress JSON API, Caching, Extensibility, User and Role Management, Templates, and URL Rewriting.
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!
Everyone talks about raising the bar on quality of code, but it's always hard to start implementing it when you have no clue where to start. With this talk I'm shooing that there are many levels developers can improve themselves by using the right tools. In this talk I'll go over each tool with examples how to use them against your codebase. A must attend talk for every developer that wants to scale up their quality. Most PHP developers deploy code that does what the customer requested but they don't have a clue about the quality of the product they deliver. Without this knowledge, maintenance can be a hell and very expensive. In this workshop I cover unit testing, code measuring, performance testing, debugging and profiling and give tips and tricks how to continue after this workshop.
Come to this talk prepared to learn about the Doctrine PHP open source project. The Doctrine project has been around for over a decade and has evolved from database abstraction software that dates back to the PEAR days. The packages provided by the Doctrine project have been downloaded almost 500 million times from packagist. In this talk we will take you through how to get started with Doctrine and how to take advantage of some of the more advanced features.
Too few projects demand good API design as a critical goal. A clean and
extensible API will pay for itself many times over in fostering a community of
plugins. We certainly cannot anticipate the ways in which our users will bend
our modules, but designing an extensible system alleviates the pain. There are
many lessons to be learned from Moose, HTTP::Engine and IM::Engine,
Dist::Zilla, KiokuDB, Fey, and TAEB.
The most important lesson is to decouple the core functionality from the
"fluff" such as sugar and middleware. This forces you to have a solid API that
ordinary users can extend. This also lets users write their own sugar and
middleware. In a tightly-coupled system, there is little hope for
extensibility.
In this talk, you will learn how to make very productive use of Moose's roles
to form the foundation of a pluggable system. Roles provide excellent means of
code reuse and safe composition. I will also demonstrate how to use
Sub::Exporter to construct a more useful and flexible sugar layer.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
The Indian economy is classified into different sectors to simplify the analysis and understanding of economic activities. For Class 10, it's essential to grasp the sectors of the Indian economy, understand their characteristics, and recognize their importance. This guide will provide detailed notes on the Sectors of the Indian Economy Class 10, using specific long-tail keywords to enhance comprehension.
For more information, visit-www.vavaclasses.com
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
We all have good and bad thoughts from time to time and situation to situation. We are bombarded daily with spiraling thoughts(both negative and positive) creating all-consuming feel , making us difficult to manage with associated suffering. Good thoughts are like our Mob Signal (Positive thought) amidst noise(negative thought) in the atmosphere. Negative thoughts like noise outweigh positive thoughts. These thoughts often create unwanted confusion, trouble, stress and frustration in our mind as well as chaos in our physical world. Negative thoughts are also known as “distorted thinking”.
This is a presentation by Dada Robert in a Your Skill Boost masterclass organised by the Excellence Foundation for South Sudan (EFSS) on Saturday, the 25th and Sunday, the 26th of May 2024.
He discussed the concept of quality improvement, emphasizing its applicability to various aspects of life, including personal, project, and program improvements. He defined quality as doing the right thing at the right time in the right way to achieve the best possible results and discussed the concept of the "gap" between what we know and what we do, and how this gap represents the areas we need to improve. He explained the scientific approach to quality improvement, which involves systematic performance analysis, testing and learning, and implementing change ideas. He also highlighted the importance of client focus and a team approach to quality improvement.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
2. Walther Lalk
CakePHP core team member
Croogo core team member
Lead Software Developer at
Troop Scouter at 9th Pretoria
(Irene) Air Scouts
Husband
3. Development environment
VirtualBox withVagrant
Recommended vagrant box is the FriendsOfCake
vagrant box.
Download it by running
$ git clone https://github.com/FriendsOfCake/vagrant-chef.git
Then start the vagrant box up with
$ cd vagrant-chef
$ vagrant up
$ vagrant ssh (For windows you’ll probably need
to use Putty)
Add this to your hosts file
192.168.13.37 app.dev
Linux or OSX : /etc/hosts
Windows:
C:WindowsSystem32driversetchosts
PHP built in server
Ensure you have PHP 5.5.9+ with the Intl and
Mbstring and a database server running (with
the corresponding PDO extension).
Supported:
MySQL,
PostgreSQL,
SQLite,
SQL Server
I will be using this with SQLite.
9. Database configuration
If you’re using the Vagrant box, and have a green tick for database, then you’re good to go.
PHP Server users probably need to do some config. Recommend simply using SQLite (It’s the easiest
to get going).
Open config/app.php
Find the Datasources, replace the default datasource with
'default' => [
'className' => 'CakeDatabaseConnection',
'driver' => 'CakeDatabaseDriverSqlite',
'database' => ROOT . DS . 'database.sqlite',
'encoding' => 'utf8',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
],
11. Bake a database
The migration bake task can sometimes get confused with composite primary keys, and tries to
make each primary key an autoincrement field. We need to fix that!
Open config/Migrations/…_CreateEventsMembers.php and remove the two
‘autoIncrement’ => true, lines.
If you are using SQLite, you need to open all the files in the config/Migrations, and change all
instances of ‘default’ => null to be ‘default’ => ‘’
12. Seed that database
$ bin/cake bake seed Members
Open config/Seeds/MembersSeed.php, and update the $data variable
$data = [
[
'first_name' => 'Walther',
'last_name' => 'Lalk',
'email' => 'waltherlalk@cakephp.org',
'created' => date('Y-m-d H:i:s'),
'modified' => date('Y-m-d H:i:s'),
]
];
13. Seed that database
$ bin/cake bake seed Events
Open config/Seeds/EventsSeed.php, and update the $data variable
$data = [
[
'title' => 'PHP South Africa 2016',
'description' => '',
'start' => '2016-09-28 08:00',
'end' => '2016-09-30 17:00',
'created' => date('Y-m-d H:i:s'),
'modified' => date('Y-m-d H:i:s'),
]
];
15. Bake your application
$ bin/cake bake all Members
$ bin/cake bake all Events
Visit /members in your browser, there should be 1 member. Add another one.
Now visit /events in your browser, there should be 1 event. Add another one.
Notice how both of them have a multi-select box for members or events? We’re going to remove
that at a later stage and change how it works.
20. Application rules
public function buildRules(RulesChecker $rules)
{
$rules->add(
function (Event $event) {
return $event->start <= $event->end;
},
'endAfterStart',
[
'errorField' => 'end',
'message' => 'The event cannot end before it has started'
]
);
return parent::buildRules($rules);
}
22. Adding a password
$ bin/cake bake migration AddPasswordToMembers password:string[60]
$ bin/cake migrations migrate
Add to src/Model/Entity/MemberEntity.php
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return (new CakeAuthDefaultPasswordHasher())->hash($password);
}
return $this->password;
}
23. Adding a password
Add to src/Templates/Members/add.ctp and src/Templates/Members/edit.ctp
echo $this->Form->input('password', [
'value' => ''
]);
echo $this->Form->input('password_confirm', [
'label' => 'Confirm password',
’type' => 'password',
'value' => ''
]);
24. Adding a password
Add validation to the password, and password confirmation fields.
$validator
->requirePresence('password', 'create')
->notEmpty('password', 'You need to provide a password.', 'create')
->minLength('password', 6, 'Your password must be 6 characters or longer');
$condition = function ($context) {
return !empty($context['data']['password']);
};
$validator
->requirePresence('password_confirm', $condition)
->notEmpty('password_confirm', 'Please confirm your password', $condition)
->add('password_confirm', 'mustMatch', [
'rule' => function ($check, $context) {
return $context['data']['password'] === $check;
},
'on' => $condition,
'message' => 'Password does not match'
]);
25. Adding a password
Edit your existing members and give them passwords. They will be automatically hashed.
26. Creating the login action
Open src/Controller/MembersController.php
public function login()
{
if ($this->request->is('post')) {
$member = $this->Auth->identify();
if ($member) {
$this->Auth->setUser($member);
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error(__('Email address or password is incorrect'), [
'key' => 'auth'
]);
}
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
28. Enabling Authentication
Open src/Controller/AppController.php, and add to the initialize method.
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Members',
'action' => 'login',
],
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email', 'password' => 'password'],
'userModel' => 'Members'
]
]
]);
Try to visit /members now
29. Event security
We are adding a organiser to our events. Only the organiser is allowed to change the event.
$ bin/cake bake migration AddOrganiserToEvents organiser_id:integer
$ bin/cake migrations migrate
$this->belongsTo('Organiser', [
'foreignKey' => 'organiser_id',
'className' => 'Members'
]);
Open src/Model/Table/EventsTable.php, and add to the initialize method.
Open src/Model/Table/MembersTable.php, and add to the initialize method.
$this->hasMany('OrganisingEvents', [
'foreignKey' => 'organiser_id',
'className' => 'Events'
]);
30. Event security
Enforce foreign key constraints at an application level by adding the following to the buildRules
method in the EventsTable class.
$rules->existsIn('organiser_id', 'Organiser', 'That member does not exist in the database.');
31. Who’s the organiser?
The member creating the event should be able to choose who the event organiser is.
In src/Templates/Events/add.ctp
echo $this->Form->input('organiser_id', [
'empty' => '-- Select organiser --',
'options' => $members,
'default' => $this->request->session()->read('Auth.User.id')
]);
In src/Templates/Events/edit.ctp
echo $this->Form->input('organiser_id', [
'empty' => '-- Select organiser --',
'options' => $members,
]);
32. Who’s that?
Who is organiser 1?
protected $_virtual = [
'full_name'
];
protected function _getFullName()
{
return sprintf('%s %s (%s)', $this->first_name, $this->last_name, $this->email);
}
Add to the Member entity class
In the MembersTable class, change the displayField to ‘full_name’
Better!
33. Event security
To enforce that an event can only be modified by it’s organiser, open
src/Controller/EventsController.php and add to the edit method, just after the get() call.
if ($event->organiser_id !== $this->Auth->user('id')) {
throw new ForbiddenException();
}
34. Member security
To prevent a member from editing another member’s profile, simply add
if ($id !== $this->Auth->user('id')) {
throw new ForbiddenException();
}
To the edit method in the MembersController.
35. Allow registrations
Allow new members to register by adding a beforeFilter method to the MembersController.
public function beforeFilter(CakeEventEvent $event)
{
$this->Auth->allow('add');
return parent::beforeFilter($event);
}
Add make a pretty URL for registration and login. Add to config/routes.php
$routes->connect('/register', ['controller' => 'Members', 'action' => 'add']);
$routes->connect('/login', ['controller' => 'Members', 'action' => 'login']);
37. Belongs to many
Create a join table object
$ bin/cake bake model EventsMembers
Change
'joinTable' => 'events_members'
to
'through' => 'EventsMembers',
'saveStrategy' => CakeORMAssociationBelongsToMany::SAVE_APPEND
in the Members and Events table objects.
38. Event attendance
Add a field to capture the type of event attendance
$ bin/cake bake migration AddTypeToEventsMembers type:string[10]
$ bin/cake migrations migrate
Add to EventsMember entity
const TYPE_GOING = 'going';
const TYPE_INTERESTED = 'interested';
const TYPE_NOT_GOING = 'notGoing';
39. Event attendance
In EventsTable, add
public function linkMember(AppModelEntityEvent $event, $memberId, $type)
{
$member = $this->Members->get($memberId);
//Add the join data
$member->_joinData = new AppModelEntityEventsMember([
'type' => $type
]);
return $this->association('Members')->link($event, [$member]);
}
40. Event attendance
In EventsController, add
public function linkActiveMember($eventId, $type)
{
$event = $this->Events->get($eventId);
if ($this->Events->linkMember($event, $this->Auth->user('id'), $type)) {
$this->Flash->success('Registered!');
} else {
$this->Flash->error('Something went wrong.');
}
return $this->redirect($this->referer());
}
41. Event attendance
In the Event entity
public function memberStatus($memberId, $type)
{
if (!$this->has('members')) {
return false;
}
$member = collection($this->members)
->firstMatch(['id' => $memberId]);
if (!$member) {
return false;
}
return $member->_joinData->type === $type;
}
43. Event attendance
Open src/Templates/Events/add.ctp and src/Templates/Events/edit.ctp and remove
echo $this->Form->input('members._ids', ['options' => $members]);
Open src/Templates/Members/add.ctp and src/Templates/Members/edit.ctp and remove
echo $this->Form->input('events._ids', ['options' => $events]);
48. Adding back functionality
Create a AuthListener class in the src/Listener directory
<?php
namespace AppListener;
use CakeEventEvent;
use CakeNetworkExceptionForbiddenException;
use CrudListenerBaseListener;
/**
* Class AuthListener
*/
class AuthListener extends BaseListener
{
/**
* Settings
*
* @var array
*/
protected $_defaultConfig = [
'property' => 'id',
'message' => 'You are not allowed to access the requested resource.',
'actions' => ['edit', 'delete']
];
49. Adding back functionality
public function afterFind(Event $event)
{
if (!in_array($this->_request()->param('action'), $this->config('actions'))
) {
return;
}
$entity = $event->subject()->entity;
$userId = $this->_controller()->Auth->user('id');
if ($entity->get($this->config('property')) !== $userId) {
throw new ForbiddenException($this->config('message'));
}
}
}
50. Adding back functionality
MembersController beforeFilter, add:
$this->Crud->addListener('Auth', 'Auth', [
'property' => 'id'
]);
Add a beforeFilter for EventsController
public function beforeFilter(CakeEventEvent $event)
{
$this->Crud->addListener('Auth', 'Auth', [
'property' => 'organiser_id'
]);
return parent::beforeFilter($event);
}