Pliki i style do korekty:
Kategoria: cakePHP 3
cakephp 3 – weak password
Jeśli baza haseł pochodzi z zewnętrznej aplikacji i jest skrótem sha1 to aby Cake skutecznie użył Fallback’u – trzeba wyłączyć sól.
Cake/Auth/WeakPasswordHasher.php
public function hash($password)
{
return Security::hash($password, $this->_config['hashType'], true);
}
true zamienić na false - nie będzie używał Security::salt
https://api.cakephp.org/3.0/source-class-Cake.Auth.WeakPasswordHasher.html#21-72
cake DebugKit
Application.php : bootstrap()
if ( Configure::read('debug') ) {
Configure::write('DebugKit.forceEnable', true);
$this->addPlugin(\DebugKit\Plugin::class);
}
cake new project
# cd /var/www/html
# curl -s https://getcomposer.org/installer | php
# mv composer.phar /usr/local/bin/composer
# composer create-project --prefer-dist cakephp/app cms
#composer require twbs/bootstrap:4.3.0
file-storage plugin
# composer require imagine/imagine
# composer require cakephp/migrations
# composer require burzum/file-storage:2.*
# cake migrations migrate -p Burzum/FileStorage
cake pdf szablony
Templates/Layout/pdf/default.ctp
updateAll – expression
Aktualizuje wiele rekordów
function publishAllUnpublished() { $this->updateAll( [ // fields 'published' => true, 'publish_date' => FrozenTime::now() ], [ // conditions 'published' => false ] ); }
RichFilemanager
Instalacja cake
# php composer.phar create-project --prefer-dist cakephp/app media77
debug
echo "<pre>". print_r($query, 1) ."</pre>"; exit;
Zmiana bazy danych
class ArticlesTable extends Table { public static function defaultConnectionName() { return 'replica_db' ; } }
cakePHP – logowanie autoryzacji
app.php w sekcji Log => [
'auth' => [ 'className' => 'Cake\Log\Engine\FileLog', 'path' => LOGS, 'file' => 'auth', 'url' => env('LOG_AUTH_URL', null), 'scopes' => ['auth'], ],
cakephp PDF wkhtmltopdf
https://wkhtmltopdf.org
https://github.com/FriendsOfCake/CakePdf
Pobrać plik instalacyjny silnika ze strony i zainstalować
# dpkg -i wkhtmltox_0.12.5-1.stretch_amd64.deb
Podlinkować do domyślnej lokalizacji
# ln -s /usr/local/bin/wkhtmltopdf /usr/bin/wkhtmltopdf
cakePHP updateAll
use Cake\Database\Expression\QueryExpression; ... function incrementCounters() { $expression = new QueryExpression('view_count=view_count +1'); $this->updateAll([$expression], ['published' => true]); }
cakephp buildRules
// In src/Model/Table/OrdersTable.php public function buildRules(RulesChecker $rules) { $check = function($order) { if($order->shipping_mode !== 'free') { return true; } return $order->price >= 100; }; $rules->add($check, [ 'errorField' => 'shipping_mode' , 'message' => 'Nie ma bezpłatnej dostawy poniżej 100zł' ]); return $rules; } // W kontrolerze $order->price = 50; $order->shipping_mode = 'free' ; $ordersTable->save($order); // Returns false
cakePHP validator password compare
// In src/Model/Table/UsersTable.php public function validatePasswords($validator) { $validator->add('password2', 'no-misspelling' , [ 'rule' => [ 'compareWith' , 'password' ], 'message' => 'Hasła nie są takie same.' , ]); ... return $validator; }
CakePHP – loadInto() – lazy loading
Dołączenie modeli do pobranego już zasobu
$articles = $this->Articles->find()->all(); $withMore = $this->Articles->loadInto($articles, ['Comments', 'Users']);
CakePHP – CounterCache
Przechowuje w tabeli ilość rekordów podrzędnych (dzieci). Definiowany jest na tabeli podrzędnej ( belongsTo() ). Tabela nadrzędna musi mieć kolumnę typu int (np. comment_count)
class CommentsTable extends Table { public function initialize(array $config) { $this->belongsTo('Articles'); $this->addBehavior('CounterCache' , [ 'Articles' => [ 'comment_count' ] ]); } }
Można zastosować CounterCache w powiązaniach belongsToMany() tylko z opcją through. Wówczas behaviour definiuje się w tabeli łączącej gdyż posiada powiązania belongsTo().
Wprowadzenie warunku – zlicza tylko komentarze bez spamu
$this->addBehavior('CounterCache' , [ 'Articles' => [ 'comment_count' => [ 'conditions' => [ 'Comments.spam' => false] ] ] ]);
CakePHP – Tree behaviour
Obsługuje złożone struktury hierarchiczne. Zapewnia wiele metod dostępu, prezentacji, generowania list, ścieżek i manipulacji elementami.
Kolumny wymagane w tabeli
parent_id lft rght level - przechowuje poziom (opcjonalna) model - lub country własna kolumna dla opcji skope (opcjonalna)
CakePHP – entity properties
Dostępne do zmiany przez formularz
class User extends Entity
{
protected $_accessible = [
'id' => false,
'*' => true
]
}
$article->accessible('title' , false); $article->set($properties, [ 'guard' => false]);
Właściwości wirtualne uwzgl. w konwersji na array/json
class User extends Entity
{
protected $_virtual = [ 'full_name' ];
}
$user->virtualProperties([ 'full_name' , 'is_admin' ]);
Nie będą exportowane do formatu array/json
class User extends Entity
{
protected $_hidden = [ 'password' ];
}
$user->hiddenProperties([ 'password' , 'recovery_question' ]);
CakePHP – badanie właściwości
$article->has('title' ); // czy jest i czy ma wartość $article->isEmpty('title' ); // czy jest pusta $article->hasValue('title' ); // czy ma wartość $article->isNew(); // nie zapisany jeszcze w bazie $article->isDirty('title' ); // czy zmieniono title $article->comments[] = $newComment; $article->setDirty('comments' , true); // ustaw - zmieniono $dirtyFields = $entity->getDirty(); // pobierz wszystkie falgi $article->clean(); // wyczyść wszystkie flagi dirty
$entity->unsetProperty('name'); $user->unsetProperty('beers'); // user belongsToMany beers $user->has('beers'); // false // Aby znowu mieć dostęp - ładujemy ręcznie $user= $this->Programmers->loadInto($user, ['Beers']);
CakePHP – virtual property
Definiowanie właściwości wirtualnej (nie będzie zapisana do bazy)
protected function _getFullName() { return $this->_properties[ 'first_name' ] . ' ' . $this->_properties[ 'last_name' ]; }
echo $user->full_name;
CakePHP – druga baza danych
Cake – korzystanie z drugiej bazy danych
namespace App\Model\Table; use Cake\ORM\Table; class ArticlesTable extends Table { public static function defaultConnectionName() { return 'replica_db' ; } }
cakephp 3 – używanie daty
$user['age'] = $user['birth_date']->diff(new \DateTime)->y;
$this->request
$controllerName = $this->request->getParam('controller' ); $params = $this->request->getAttribute('params' ); $passedArgs = $this->request->getParam('pass' ); // URL is /posts/index?page=1&sort=title $page = $this->request->getQuery('page' ); $query = $this->request->getQueryParams(); // Input with a name 'MyModel[title]' $title = $this->request->getData('MyModel.title' ); $host = $this->request->env('HTTP_HOST' ); $env = $this->request->getServerParams(); // /subdir/articles/edit/1?page=1 $here = $request->getRequestTarget(); $base = $request->getAttribute('base'); // /subdir $base = $request->getAttribute('webroot'); // /subdir/ $jsonData = $this->request->input('json_decode' ); $data = $this->request->input('Cake\Utility\Xml::build' , [ 'return' => 'domdocument' ]); $this->request->is('post') $this->request->is('ajax') // X-Requested-With = XMLHttpRequest $this->request->is('json') // application/xml lub text/xml .json (ext) $userName = $this->request->session() ->read('Auth.User.name' );
$request->domain(); $request->subdomains(); $request->host(); $request->getMethod(); $this->request->allowMethod([ 'post' , 'delete']);
CakePHP 3 – konfiguracja
Strefa czasowa: config/bootstrap.php
date_default_timezone_set('Europe/Warsaw');
CakePHP 3 – Date
W kontrolerze:
use Cake\I18n\Date;
Przy kopiowaniu rekordu na następny miesiąc przesuwa datę o 1 miesiąc:
$data = new Date( $record->data ); $data->modify('+1 month');
CakePHP 3 instalacja
# curl -s https://getcomposer.org/installer | php
# php composer.phar create-project --prefer-dist cakephp/app projekty
- /config/app
- baza danych: Datasources => default => (host, user, password, dbname)
- Security: zmienić ciąg security salt
- /config/bootstrap.php
- date_default_timezone_set(’Europe/Warsaw’);
# cd projekty # bin/cake bake all users # bin/cake bake all projects # bin/cake bake all groups