### Install Dependencies and Start Dev Server Source: https://github.com/cakephp/docs/blob/5.x/README.md Installs project dependencies and starts the VitePress development server for local documentation viewing with hot-reloading. ```bash npm install npm run docs:dev ``` -------------------------------- ### Start Development Server with Docker Source: https://github.com/cakephp/docs/blob/5.x/docs/en/installation.md Starts the PHP development server inside a Docker container, installing necessary extensions and exposing the port. ```bash # Start PHP development server (install required extensions first) cd my_app docker run -it --rm -p 8765:8765 -v $(pwd):/app \ -w /app php:8.2-cli bash -c "apt-get update && apt-get install -y libicu-dev && docker-php-ext-install intl mbstring && php bin/cake server -H 0.0.0.0" ``` -------------------------------- ### Install CSP Builder Source: https://github.com/cakephp/docs/blob/5.x/docs/en/security/content-security-policy.md Install the paragonie/csp-builder package using Composer before configuring the middleware. ```bash composer require paragonie/csp-builder ``` -------------------------------- ### Install Dependencies with Composer Source: https://github.com/cakephp/docs/blob/5.x/docs/en/deployment.md On each deploy, install project dependencies using `composer install`. Avoid `composer update` during deploys to prevent unexpected package version changes. ```bash composer install ``` -------------------------------- ### YAML Frontmatter Example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/contributing/documentation.md Basic YAML frontmatter for page metadata, including title and description. Must be at the start of the file. ```yaml --- title: Page Title description: A brief description of the page content --- ``` -------------------------------- ### ProgressHelper setUp Method Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/testing.md Implementation of the setUp method to initialize the helper. ```php public function setUp(): void { parent::setUp(); $View = new View(); $this->Progress = new ProgressHelper($View); } ``` -------------------------------- ### Install Composer on Windows Source: https://github.com/cakephp/docs/blob/5.x/docs/en/installation.md Installs Composer on Windows systems by downloading and running the official installer. ```powershell # Download and run the Windows installer # https://getcomposer.com/Composer-Setup.exe # Verify installation composer --version ``` -------------------------------- ### Start the Server Command Source: https://github.com/cakephp/docs/blob/5.x/docs/en/console-commands/server.md Run the server command to start the development webserver. The server will attach to port 8765 by default. Close the server by pressing CTRL-C. ```bash bin/cake server ``` -------------------------------- ### Install Composer Source: https://github.com/cakephp/docs/blob/5.x/docs/en/tutorials-and-examples/cms/installation.md Install Composer, a dependency manager for PHP, using cURL on Linux/macOS. For Windows, use the provided installer. ```bash curl -s https://getcomposer.org/installer | php ``` ```bash # Download and run the Composer Windows Installer # https://getcomposer.org/Composer-Setup.exe ``` -------------------------------- ### Lazy Load Association Example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/orm/entities.md Demonstrates how to access a lazy-loaded association. Ensure the LazyLoad plugin is installed and configured. ```php $article = $this->Articles->findById($id); // The comments property was lazy loaded foreach ($article->comments as $comment) { echo $comment->body; } ``` -------------------------------- ### Example Translation File (PO format) Source: https://github.com/cakephp/docs/blob/5.x/docs/en/core-libraries/internationalization-and-localization.md This is an example of a .po file used for translations. It includes placeholders for dynamic content like numbers and names. ```pot msgid "My name is {0}" msgstr "Je m'appelle {0}" msgid "I'm {0,number} years old" msgstr "J'ai {0,number} ans" ``` -------------------------------- ### Install Authorization Plugin Source: https://github.com/cakephp/docs/blob/5.x/docs/en/tutorials-and-examples/cms/authorization.md Use composer to install the Authorization plugin. Ensure you are using version 3.0 or higher. ```bash composer require "cakephp/authorization:^3.0" ``` -------------------------------- ### Install and Run CakePHP Upgrade Tool Source: https://github.com/cakephp/docs/blob/5.x/docs/en/appendices/migration-guides.md Install the upgrade tool by cloning the repository and running composer install. Then, use the `bin/cake upgrade rector` command with the appropriate ruleset for your target version and specify the application path. ```bash git clone https://github.com/cakephp/upgrade cd upgrade git checkout 5.x composer install --no-dev bin/cake upgrade rector --rules cakephp52 ``` -------------------------------- ### Start Development Server with FrankenPHP Source: https://github.com/cakephp/docs/blob/5.x/docs/en/appendices/5-3-migration-guide.md Use the `--frankenphp` option with `cake server` to start the development server using FrankenPHP. ```bash cake server --frankenphp ``` -------------------------------- ### Install Composer on Linux/macOS Source: https://github.com/cakephp/docs/blob/5.x/docs/en/installation.md Installs Composer globally on Linux or macOS systems using curl. ```bash # Linux/macOS curl -sS https://getcomposer.org/installer | php sudo mv composer.phar /usr/local/bin/composer # Verify installation composer --version ``` -------------------------------- ### Install and Use Documentation Validation Tools Source: https://github.com/cakephp/docs/blob/5.x/docs/en/contributing/documentation.md Install or use npx to run cspell for spell checking and markdownlint-cli2 for markdown formatting consistency. Recommended for local development and CI. ```bash # No installation needed - npx downloads and runs the tools npx cspell --config .github/cspell.json "docs/en/**/*.md" npx markdownlint-cli2 --config .github/.markdownlint-cli2.jsonc "docs/en/**/*.md" ``` ```bash # Install globally for faster execution npm install -g cspell markdownlint-cli2 # Then run without npx cspell --config .github/cspell.json "docs/en/**/*.md" markdownlint-cli2 --config .github/.markdownlint-cli2.jsonc "docs/en/**/*.md" ``` -------------------------------- ### Start CakePHP Development Server Source: https://github.com/cakephp/docs/blob/5.x/docs/en/tutorials-and-examples/cms/installation.md Navigate to your application directory and start the built-in CakePHP development server. This is useful for local testing. ```bash cd /path/to/our/app bin/cake server ``` ```bash cd C:\path\to\our\app bin\cake server ``` -------------------------------- ### OrdersTable and CartsTable example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/testing.md Example of OrdersTable and CartsTable demonstrating event dispatching and listening. ```php class OrdersTable extends Table { public function place($order): bool { if ($this->save($order)) { // moved cart removal to CartsTable $event = new Event('Model.Order.afterPlace', $this, [ 'order' => $order, ]); $this->getEventManager()->dispatch($event); return true; } return false; } } class CartsTable extends Table { public function initialize(): void { // Models don't share the same event manager instance, // so we need to use the global instance to listen to // events from other models \Cake\Event\EventManager::instance()->on( 'Model.Order.afterPlace', callable: [$this, 'removeFromCart'], ); } public function removeFromCart(EventInterface $event): void { $order = $event->getData('order'); $this->delete($order->cart_id); } } ``` -------------------------------- ### HtmlHelper Attribute Examples Source: https://github.com/cakephp/docs/blob/5.x/docs/en/views/helpers/html.md Demonstrates how to pass attributes to HtmlHelper methods using arrays. ```html Desired attributes: Array parameter: ['class' => 'someClass'] Desired attributes: Array parameter: ['name' => 'foo', 'value' => 'bar'] ``` -------------------------------- ### ArticlesController Example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/testing.md An example of an ArticlesController class that handles GET and POST requests. ```php namespace App\Controller; use App\Controller\AppController; class ArticlesController extends AppController { public function index($short = null) { if ($this->request->is('post')) { $article = $this->Articles->newEntity($this->request->getData()); if ($this->Articles->save($article)) { // Redirect as per PRG pattern return $this->redirect(['action' => 'index']); } } if (!empty($short)) { $result = $this->Articles->find('all', fields: ['id', 'title'])->all(); } else { $result = $this->Articles->find()->all(); } $this->set([ 'title' => 'Articles', 'articles' => $result, ]); } } ``` -------------------------------- ### Preview Production Build Locally Source: https://github.com/cakephp/docs/blob/5.x/README.md Locally previews the production-ready static documentation site. ```bash npm run docs:preview ``` -------------------------------- ### Sample XML Help Output Source: https://github.com/cakephp/docs/blob/5.x/docs/en/console-commands/option-parsers.md This is an example of the XML structure generated for command help, including commands, descriptions, epilogs, options, and arguments. ```xml bake fixture Generate fixtures for use with the test suite. You can use `bake fixture all` to bake all fixtures. Omitting all arguments and options will enter into an interactive mode. ``` -------------------------------- ### Indentation Example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/contributing/cakephp-coding-conventions.md Demonstrates the four-space indentation rule for nested code blocks. ```php // base level // level 1 // level 2 // level 1 // base level ``` -------------------------------- ### Get HTTP Method Source: https://github.com/cakephp/docs/blob/5.x/docs/en/controllers/request-response.md Retrieve the HTTP method used for the request. No specific setup is required. ```php // Output POST echo $request->getMethod(); ``` -------------------------------- ### Configuring Components to Load Source: https://github.com/cakephp/docs/blob/5.x/docs/en/controllers.md Shows how to load and configure components within a controller's `initialize()` method. ```APIDOC ## GET /api/users/{id} ### Description Retrieves the details of a specific user by their ID. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "id": 1, "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Configure Custom Log Engine from Application Source: https://github.com/cakephp/docs/blob/5.x/docs/en/core-libraries/logging.md Set up a custom log engine like 'Database' located in src/Log/Engine/DatabaseLog.php. ```php Log::setConfig('otherFile', [ 'className' => 'Database', 'model' => 'LogEntry', // ... ]); ``` -------------------------------- ### Get Help for Plugin Tool Source: https://github.com/cakephp/docs/blob/5.x/docs/en/console-commands/plugin.md Run this command to see all available options and tasks for the plugin tool. ```bash bin/cake plugin --help ``` -------------------------------- ### Get date range for a quarter Source: https://github.com/cakephp/docs/blob/5.x/docs/en/core-libraries/time.md Retrieve the start and end dates for a given quarter using toQuarterRange(). Returns an array with two date strings. ```php $time = new DateTime('2021-01-31'); $range = $time->toQuarterRange(); // Outputs ['2021-01-01', '2021-03-31'] ``` ```php $time = new DateTime('2021-12-25'); $range = $time->toQuarterRange(); // Outputs ['2021-10-01', '2021-12-31'] ``` -------------------------------- ### Get Quarter Date Range Source: https://github.com/cakephp/docs/blob/5.x/docs/en/appendices/5-3-migration-guide.md The `toQuarterRange()` method on `DateTime` and `FrozenTime` returns an array containing the start and end dates of the quarter for a given date. ```php $quarterDates = $frozenTime->toQuarterRange(); ``` -------------------------------- ### Build Documentation with Docker Source: https://github.com/cakephp/docs/blob/5.x/README.md Builds the documentation site using a Docker container, ensuring all necessary packages are present. Uses --progress=plain and --no-cache for a clean build. ```bash docker build --progress=plain --no-cache -f Dockerfile -t cake-docs . ``` -------------------------------- ### Modify Entities with Model.afterMarshal (Custom Validation) Source: https://github.com/cakephp/docs/blob/5.x/docs/en/orm/saving-data.md The `Model.afterMarshal` event allows you to modify entities after they are created from request data. This example demonstrates applying custom validation logic, preventing entities with names starting with 'J' from being saved on the 20th of the month by setting an error. ```php use Cake\Event\EventInterface; use Cake\ORM\EntityInterface; use ArrayObject; // In a table or behavior class public function afterMarshal( EventInterface $event, EntityInterface $entity, ArrayObject $data, ArrayObject $options, ): void { // Don't accept people who have a name starting with J on the 20th // of each month. if (mb_substr($entity->name, 1) === 'J' && (int)date('d') === 20) { $entity->setError('name', 'No J people today sorry.'); } } ``` -------------------------------- ### Plugin Syntax Examples Source: https://github.com/cakephp/docs/blob/5.x/docs/en/appendices/glossary.md Demonstrates the dot-separated class name syntax for referencing classes within plugins. Supports both simple and namespaced plugin names. ```php // The plugin is "DebugKit", and the class name is "Toolbar". 'DebugKit.Toolbar' ``` ```php // The plugin is "AcmeCorp/Tools", and the class name is "Toolbar". 'AcmeCorp/Tools.Toolbar' ``` -------------------------------- ### Define GET Route in CakePHP Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/routing.md Use the `get()` method to create a route that only responds to GET requests. This is useful for fetching resources. ```php // Create a route that only responds to GET requests. $routes->get( '/cooks/{id}', ['controller' => 'Users', 'action' => 'view'], 'users:view', ); ``` -------------------------------- ### Create a Bootable Service Provider Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/dependency-injection.md Implement the bootstrap() method in a service provider to run logic when it's added to the container. This is useful for loading additional configurations or providers. ```php namespace App\ServiceProvider; use Cake\Core\ServiceProvider; // Other imports here. class BillingServiceProvider extends ServiceProvider { protected array $provides = [ StripeService::class, 'configKey', ]; public function bootstrap(ContainerInterface $container): void { $container->addServiceProvider(new InvoicingServiceProvider()); } } ``` -------------------------------- ### Make Simple GET Requests Source: https://github.com/cakephp/docs/blob/5.x/docs/en/core-libraries/httpclient.md Use the `get()` method to perform simple GET requests. You can include query string parameters and additional headers. ```php use Cake\Http\Client; $http = new Client(); // Simple get $response = $http->get('https://example.com/test.html'); // Simple get with querystring $response = $http->get('https://example.com/search', ['q' => 'widget']); // Simple get with querystring & additional headers $response = $http->get('https://example.com/search', ['q' => 'widget'], [ 'headers' => ['X-Requested-With' => 'XMLHttpRequest'], ]); ``` -------------------------------- ### Build Static Documentation Site Source: https://github.com/cakephp/docs/blob/5.x/README.md Builds the static version of the documentation site for production deployment. ```bash npm run docs:build ``` -------------------------------- ### Interact with Application Models Source: https://github.com/cakephp/docs/blob/5.x/docs/en/console-commands/repl.md Once the console is running, you can fetch and query your application's models. This example retrieves the 'Articles' table and finds all records. ```bash bin/cake console >>> $articles = Cake\Datasource\FactoryLocator::get('Table')->get('Articles'); // object(Cake\ORM\Table)( // // ) >>> $articles->find()->all(); ``` -------------------------------- ### Set and Get Entity Data Source: https://github.com/cakephp/docs/blob/5.x/docs/en/orm/entities.md Use the set() and get() methods for programmatic control over entity data. set() assigns a value to a field, and get() retrieves it. ```php $article->set('title', 'This is my first post'); echo $article->get('title'); ``` -------------------------------- ### Collection Creation and Basic Usage Source: https://github.com/cakephp/docs/blob/5.x/docs/en/core-libraries/collections.md Demonstrates how to create a Collection instance and perform a basic filter operation. ```APIDOC ## Collection Creation and Basic Usage ### Description Collections can be created using an array or `Traversable` object. This example shows how to instantiate a Collection and use the `filter` method. ### Method `new Collection($items)` or `collection($items)` ### Endpoint N/A (Class instantiation) ### Request Example ```php use Cake\Collection\Collection; $items = ['a' => 1, 'b' => 2, 'c' => 3]; $collection = new Collection($items); // Create a new collection containing elements // with a value greater than one. $overOne = $collection->filter(function ($value, $key, $iterator) { return $value > 1; }); ``` ### Response N/A (Object instantiation and method chaining) ### Example using helper function ```php $items = ['a' => 1, 'b' => 2, 'c' => 3]; // These both make a Collection instance. $collectionA = new Collection($items); $collectionB = collection($items); ``` ``` -------------------------------- ### Create Form Pointing to External URL with GET Method Source: https://github.com/cakephp/docs/blob/5.x/docs/en/views/helpers/form.md Direct the form to an external domain by providing a full URL in the 'url' option. The 'type' option can be set to 'get' for GET requests. ```php echo $this->Form->create(null, [ 'url' => 'https://www.google.com/search', 'type' => 'get', ]); ``` -------------------------------- ### Optimizer Hints Source: https://github.com/cakephp/docs/blob/5.x/docs/en/orm/query-builder.md Explains how to use `optimizerHint` to control query execution plans, noting its current support on MySQL and Postgres. ```APIDOC ## Optimizer Hints ### Description Optimizer hints allow you to control execution plans at the individual query level. Currently supported by MySQL and Postgres (via an extension). ### Method `Query::optimizerHint(array $hints)` ### Endpoint N/A (Method within a Query object) ### Parameters #### Request Body - **$hints** (array) - An array of optimizer hints to apply to the query. ### Request Example ```php $query->optimizerHint(['NO_BKA(articles)']); ``` ### Response #### Success Response (200) N/A (This is a method for building queries, not an endpoint) #### Response Example N/A ::: info Added in version 5.3.0 `Query::optimizerHint()` was added. ::: ``` -------------------------------- ### Progress Helper with Options Source: https://github.com/cakephp/docs/blob/5.x/docs/en/console-commands/input-output.md Demonstrates using the ProgressHelper with explicit 'total', 'width', and 'callback' options for more control over the progress bar. ```php $io->helper('Progress')->output([ 'total' => 10, 'width' => 20, 'callback' => function ($progress) { $progress->increment(2); $progress->draw(); } ]); ``` -------------------------------- ### Cache Configuration Example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/core-libraries/caching.md Example of configuring cache engines in config/app.php. ```php [ 'short' => [ 'className' => 'File', 'duration' => '+1 hours', 'path' => CACHE, 'prefix' => 'cake_short_', ], // Using a fully namespaced name. 'long' => [ 'className' => 'Cake\Cache\Engine\FileEngine', 'duration' => '+1 week', 'probability' => 100, 'path' => CACHE . 'long' . DS, ], ] // ... ?> ``` -------------------------------- ### Create Scoped Client from URL Source: https://github.com/cakephp/docs/blob/5.x/docs/en/core-libraries/httpclient.md Initialize a scoped client using a URL, automatically setting protocol, host, and basePath options. ```php $http = Client::createFromUrl('https://api.example.com/v1/test'); ``` -------------------------------- ### Read Configuration Data or Throw Exception Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/configuration.md Use Configure::readOrFail() to read configuration data. This method throws a RuntimeException if the requested key does not exist. ```php Configure::readOrFail('Company.name'); // Yields: 'Pizza, Inc.' Configure::readOrFail('Company.geolocation'); // Will throw an exception Configure::readOrFail('Company'); // Yields: ['name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul']; ``` -------------------------------- ### Array Results Example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/orm/query-builder.md Example of query results when hydration is disabled, showing data as an array of associative arrays. ```php [ ['id' => 1, 'title' => 'First Article', 'body' => 'Article 1 body' ...], ['id' => 2, 'title' => 'Second Article', 'body' => 'Article 2 body' ...], ... ] ``` -------------------------------- ### Loading Templates from Configuration Files Source: https://github.com/cakephp/docs/blob/5.x/docs/en/views/helpers/html.md Demonstrates how to load HTML templates from a configuration file using the templater directly. ```APIDOC ## Loading Templates from Configuration Files ### Description Loads HTML templates from a configuration file using the templater. ### Method `Cake\View\Helper\HtmlHelper::templater()->load(string $filename): void` ### Endpoint N/A (This is a method call within your application logic) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Load a configuration file with templates. $this->Html->templater()->load('my_tags'); ``` ### Response #### Success Response (200) None (This method typically does not return a value, but modifies the templater's state). ### Configuration File Example (`my_tags.php`) ```php '', ]; ``` ``` -------------------------------- ### PagematronComponent Example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/testing.md Example of a PagematronComponent that adjusts pagination limits. ```php class PagematronComponent extends Component { public ?Controller $controller = null; public function setController(Controller $controller): void { $this->controller = $controller; // Make sure the controller is using pagination if (!isset($this->controller->paginate)) { $this->controller->paginate = []; } } public function startup(EventInterface $event): void { $this->setController($event->getSubject()); } public function adjust(string $length = 'short'): void { switch ($length) { case 'long': $this->controller->paginate['limit'] = 100; break; case 'medium': $this->controller->paginate['limit'] = 50; break; default: $this->controller->paginate['limit'] = 20; break; } } } ``` -------------------------------- ### Example of CDN Usage with HtmlHelper Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/configuration.md Illustrates how HtmlHelper resolves asset URLs when App.imageBaseUrl is configured for a CDN. ```php $this->Helper->assetUrl('TestPlugin.logo.png') ``` -------------------------------- ### Configure Components in Controller Initialize Source: https://github.com/cakephp/docs/blob/5.x/docs/en/controllers/components.md Load and configure components like FormProtection and Flash within the controller's `initialize()` method. This is a common way to set up components that are needed for most actions. ```php class PostsController extends AppController { public function initialize(): void { parent::initialize(); $this->loadComponent('FormProtection', [ 'unlockedActions' => ['index'], ]); $this->loadComponent('Flash'); } } ``` -------------------------------- ### Routing Array Example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/appendices/glossary.md An example of a routing array, which contains attributes passed to `Router::url()` for generating URLs. ```php ['controller' => 'Posts', 'action' => 'view', 5] ``` -------------------------------- ### ArticlesControllerTest Example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/testing.md An example of an ArticlesController test case using IntegrationTestTrait. ```php namespace App\Test\TestCase\Controller; use Cake\TestSuite\IntegrationTestTrait; use Cake\TestSuite\TestCase; class ArticlesControllerTest extends TestCase { use IntegrationTestTrait; protected array $fixtures =['app.Articles']; public function testIndex(): void { $this->get('/articles'); $this->assertResponseOk(); // More asserts. } public function testIndexQueryData(): void { $this->get('/articles?page=1'); $this->assertResponseOk(); // More asserts. } public function testIndexShort(): void { $this->get('/articles/index/short'); $this->assertResponseOk(); $this->assertResponseContains('Articles'); // More asserts. } public function testIndexPostData(): void { $data = [ 'user_id' => 1, 'published' => 1, 'slug' => 'new-article', 'title' => 'New Article', 'body' => 'New Body', ]; $this->post('/articles', $data); $this->assertResponseSuccess(); $articles = $this->getTableLocator()->get('Articles'); $query = $articles->find()->where(['title' => $data['title']]); $this->assertEquals(1, $query->count()); } } ``` -------------------------------- ### Create a Scoped HTTP Client Source: https://github.com/cakephp/docs/blob/5.x/docs/en/core-libraries/httpclient.md Create a client instance with predefined host, scheme, and authentication settings to reduce repetitive configuration. ```php // Create a scoped client. $http = new Client([ 'host' => 'api.example.com', 'scheme' => 'https', 'auth' => ['username' => 'mark', 'password' => 'testing'], ]); // Do a request to api.example.com $response = $http->get('/test.php'); ``` -------------------------------- ### Generate Help as XML Source: https://github.com/cakephp/docs/blob/5.x/docs/en/console-commands/option-parsers.md Request help output in XML format by appending `xml` to the help flag. This is useful for machine-readable output. ```bash cake bake --help xml ``` ```bash cake bake -h xml ``` -------------------------------- ### Install CakePHP Authentication Plugin Source: https://github.com/cakephp/docs/blob/5.x/docs/en/tutorials-and-examples/cms/authentication.md Use composer to install the Authentication Plugin for CakePHP. Ensure you are using version 4.0 or later. ```bash composer require "cakephp/authentication:^4.0" ``` -------------------------------- ### Read Configuration Data with Fallback Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/configuration.md Use Configure::read() to retrieve configuration values. Provide a default value to be returned if the key does not exist. ```php // Returns 'Pizza Inc.' Configure::read('Company.name'); // Returns 'Pizza for your body and soul' Configure::read('Company.slogan'); Configure::read('Company'); // Returns: ['name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul']; // Returns 'fallback' as Company.nope is undefined. Configure::read('Company.nope', 'fallback'); ``` -------------------------------- ### Install Plugin with Composer Source: https://github.com/cakephp/docs/blob/5.x/docs/en/plugins.md Use Composer to install a plugin like DebugKit. This command updates your project's dependencies and autoloader. ```bash php composer.phar require cakephp/debug_kit ``` -------------------------------- ### Entity Instantiation and Creation Source: https://github.com/cakephp/docs/blob/5.x/docs/en/orm/entities.md Shows different ways to instantiate and create entities, including direct instantiation with data and using table object methods like `newEmptyEntity()` and `newEntity()`. ```APIDOC ## Creating Entities Entities can be directly instantiated: ```php use App\Model\Entity\Article; $article = new Article(); ``` When instantiating an entity you can pass the fields with the data you want to store in them: ```php use App\Model\Entity\Article; $article = new Article([ 'id' => 1, 'title' => 'New Article', 'created' => new DateTime('now'), ]); ``` The preferred way of getting new entities is using the `newEmptyEntity()` method from the `Table` objects: ```php use Cake\ORM\Locator\LocatorAwareTrait; $article = $this->fetchTable('Articles')->newEmptyEntity(); $article = $this->fetchTable('Articles')->newEntity([ 'id' => 1, 'title' => 'New Article', 'created' => new DateTime('now'), ]); ``` `$article` will be an instance of `App\Model\Entity\Article` or fallback to `Cake\ORM\Entity` instance if you haven't created the `Article` class. > [!NOTE] > Prior to CakePHP 4.3 you need to use `$this->getTableLocator->get('Articles')` to get the table instance. ``` -------------------------------- ### Install PHPUnit with Composer Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/testing.md Installs PHPUnit as a development dependency using Composer. ```bash php composer.phar require --dev phpunit/phpunit:"^11.5.3" ``` -------------------------------- ### Using the collection() Helper Function Source: https://github.com/cakephp/docs/blob/5.x/docs/en/core-libraries/collections.md Shows an alternative way to create a Collection instance using the `collection()` helper function, which can be more convenient for chaining operations. ```php $items = ['a' => 1, 'b' => 2, 'c' => 3]; // These both make a Collection instance. $collectionA = new Collection($items); $collectionB = collection($items); ``` -------------------------------- ### Change Form HTTP Method to GET Source: https://github.com/cakephp/docs/blob/5.x/docs/en/views/helpers/form.md Explicitly set the form's HTTP method to GET using the 'type' option. ```php echo $this->Form->create($article, ['type' => 'get']); ``` -------------------------------- ### Create a Basic Hello World Command in CakePHP Source: https://github.com/cakephp/docs/blob/5.x/docs/en/console-commands/commands.md Implement the execute() method to define the command's logic. This is the entry point when the command is invoked. ```php out('Hello world.'); return static::CODE_SUCCESS; } } ``` -------------------------------- ### OrdersTableTest example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/testing.md Example test case for OrdersTable using assertEventFired and assertEventFiredWith. ```php namespace App\Test\TestCase\Model\Table; use App\Model\Table\OrdersTable; use Cake\Event\EventList; use Cake\TestSuite\TestCase; class OrdersTableTest extends TestCase { protected array $fixtures =['app.Orders']; public function setUp(): void { parent::setUp(); $this->Orders = $this->getTableLocator()->get('Orders'); // enable event tracking $this->Orders->getEventManager()->setEventList(new EventList()); } public function testPlace(): void { $order = new Order([ 'user_id' => 1, 'item' => 'Cake', 'quantity' => 42, ]); $this->assertTrue($this->Orders->place($order)); $this->assertEventFired('Model.Order.afterPlace', $this->Orders->getEventManager()); $this->assertEventFiredWith('Model.Order.afterPlace', 'order', $order, $this->Orders->getEventManager()); } } ``` -------------------------------- ### ArticlesTableTest Setup Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/testing.md Basic setup for testing the ArticlesTable, including fixture definition. ```php namespace App\Test\TestCase\Model\Table; use App\Model\Table\ArticlesTable; use Cake\TestSuite\TestCase; class ArticlesTableTest extends TestCase { protected array $fixtures =['app.Articles']; } ``` -------------------------------- ### Configure Default Database Connection Source: https://github.com/cakephp/docs/blob/5.x/docs/en/orm/database-basics.md Sets up the default database connection using a DSN string. Ensure the database driver is installed. ```php use Cake\Datasource\ConnectionManager; $dsn = 'mysql://root:password@localhost/my_database'; ConnectionManager::setConfig('default', ['url' => $dsn]); ``` -------------------------------- ### ConnectionManager::setConfig() and get() for Runtime Connections Source: https://github.com/cakephp/docs/blob/5.x/docs/en/orm/database-basics.md Illustrates how to define and retrieve a new database connection at runtime without modifying configuration files. ```APIDOC ## Creating Connections at Runtime Using `setConfig()` and `get()` you can create new connections that are not defined in your configuration files at runtime: ```php ConnectionManager::setConfig('my_connection', $config); $connection = ConnectionManager::get('my_connection'); ``` See the [Database Configuration](#database-configuration) for more information on the configuration data used when creating connections. ``` -------------------------------- ### Get Table Instance using LocatorAwareTrait Source: https://github.com/cakephp/docs/blob/5.x/docs/ja/orm.md Use the LocatorAwareTrait to easily get an instance of a Table object, such as 'Articles', within your controllers or other classes. ```php use Cake\ORM\Locator\LocatorAwareTrait; public function someMethod() { $articles = $this->getTableLocator()->get('Articles'); // more code. } ``` -------------------------------- ### Create Files with ConsoleIo::createFile Source: https://github.com/cakephp/docs/blob/5.x/docs/en/console-commands/input-output.md Use createFile to generate files with interactive confirmation for overwrites. Set the third argument to true to force overwriting without prompting. ```php $io->createFile('bower.json', $stuff); ``` ```php $io->createFile('bower.json', $stuff, true); ``` -------------------------------- ### PaginatorHelper Example Usage Source: https://github.com/cakephp/docs/blob/5.x/docs/en/views/helpers/paginator.md Demonstrates practical examples of using the PaginatorHelper in CakePHP views for creating sortable table headers and pagination controls. ```APIDOC ## Usage Examples for PaginatorHelper ### Description Provides examples for integrating PaginatorHelper into views, including creating sortable table headers and displaying pagination navigation elements like page numbers, previous/next links, and a page counter. ### Code Examples #### Sortable Table Headers ```php
Paginator->sort('id', 'ID') ?> Paginator->sort('title', 'Title') ?>
id ?> title) ?>
``` #### Sorting by Associated Model Columns ```php
Paginator->sort('title', 'Title') ?> Paginator->sort('Authors.name', 'Author') ?>
title) ?> name) ?>
``` #### Pagination Navigation ```php // Shows the page numbers Paginator->numbers() ?> // Shows the next and previous links Paginator->prev('« Previous') ?> Paginator->next('Next »') ?> // Prints X of Y, where X is current page and Y is number of pages Paginator->counter() ?> // Customized counter output Paginator->counter( 'Page {{page}} of {{pages}}, showing {{current}} records out of {{count}} total, starting on record {{start}}, ending on {{end}}', ) ?> ``` ### Controller Configuration for Associated Sorting To enable sorting by columns in associated models, configure `PaginationComponent::paginate` in your controller: ```php $this->paginate = [ 'sortableFields' => [ 'Posts.title', 'Authors.name', ], ]; ``` ``` -------------------------------- ### Configure Basic CSP Middleware Source: https://github.com/cakephp/docs/blob/5.x/docs/en/security/content-security-policy.md Configure the CspMiddleware with an array of directives. This example sets script-src to allow Google Analytics and enforce self-referencing, while disallowing inline scripts and eval. ```php use Cake\Http\Middleware\CspMiddleware; $csp = new CspMiddleware([ 'script-src' => [ 'allow' => [ 'https://www.google-analytics.com', ], 'self' => true, 'unsafe-inline' => false, 'unsafe-eval' => false, ], ]); $middlewareQueue->add($csp); ``` -------------------------------- ### Accessing Command Helpers Source: https://github.com/cakephp/docs/blob/5.x/docs/en/console-commands/input-output.md Demonstrates how to access and use built-in command helpers like Table and Progress from the ConsoleIo object. ```php $io->helper('Table')->output($data); ``` ```php $io->helper('Plugin.HelperName')->output($data); ``` ```php $progress = $io->helper('Progress'); $progress->increment(10); $progress->draw(); ``` -------------------------------- ### Implement beforeExecute for Command Initialization Source: https://github.com/cakephp/docs/blob/5.x/docs/en/console-commands/commands.md Use beforeExecute to perform initialization and validation before a command's main logic runs. Ensure prerequisites are met, or abort execution. ```php use Cake\Event\EventInterface; class MyCommand extends Command { public function beforeExecute(EventInterface $event, Arguments $args, ConsoleIo $io): void { parent::beforeExecute($event); $io->out('Starting command execution'); if (!$this->checkPrerequisites()) { $io->abort('Prerequisites not met'); } } } ``` -------------------------------- ### ArticlesTable Class Example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/testing.md An example of a CakePHP Table class with a custom finder method. ```php namespace App\Model\Table; use Cake\ORM\Table; use Cake\ORM\Query\SelectQuery; class ArticlesTable extends Table { public function findPublished(SelectQuery $query): SelectQuery { $query->where([ $this->getAlias() . '.published' => 1, ]); return $query; } } ``` -------------------------------- ### Cache Event Listener Example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/core-libraries/caching.md An example of how to add an event listener for cache events in your Application or plugin class. ```php public function events(EventManagerInterface $eventManager): EventManagerInterface { $eventManager->on(CacheAfterGetEvent::NAME, function (CacheAfterGetEvent $event): void { $key = $event->getKey(); $value = $event->getValue(); $success = $event->getResult(); }); return $eventManager; } ``` -------------------------------- ### Extend Layout and Modify Content Block Source: https://github.com/cakephp/docs/blob/5.x/docs/en/views.md This example shows how to extend a layout and prepend/append markup to the 'content' block. It also demonstrates fetching and echoing the modified content. ```php // Our layout extends the application layout. $this->extend('application'); $this->prepend('content', '
'); $this->append('content', '
'); // Output more markup. // Remember to echo the contents of the previous layout. echo $this->fetch('content'); ``` -------------------------------- ### Code Group Example Source: https://github.com/cakephp/docs/blob/5.x/docs/en/contributing/documentation.md Displays multiple code examples side-by-side using tabs. Each tab is defined by a code block within `::: code-group`. ```markdown ::: code-group ```php [Controller] class ArticlesController extends Controller { public function index() { $articles = $this->Articles->find('all'); } } ``` ```php [Model] class ArticlesTable extends Table { public function initialize(array $config): void { $this->addBehavior('Timestamp'); } } ``` ```php [Template]

title) ?>

``` ::: ``` -------------------------------- ### Create a New Database Connection at Runtime Source: https://github.com/cakephp/docs/blob/5.x/docs/en/orm/database-basics.md Configure and create a new database connection dynamically using setConfig() and get() from ConnectionManager. This is useful for connections not defined in configuration files. ```php ConnectionManager::setConfig('my_connection', $config); $connection = ConnectionManager::get('my_connection'); ``` -------------------------------- ### Configure Apache for Subdirectory Install Source: https://github.com/cakephp/docs/blob/5.x/docs/en/installation.md Adapt Apache's rewrite rules if your CakePHP application is installed in a subdirectory, such as under a user's home directory. ```apache # If installing in a subdirectory like /~username/myapp/ RewriteEngine On RewriteBase /~username/myapp RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] ``` -------------------------------- ### Get Table Constraints and Indexes Source: https://github.com/cakephp/docs/blob/5.x/docs/en/orm/schema-system.md Retrieve the names of all constraints and indexes on a table, or get details for a specific one. Assumes a populated TableSchema instance. ```php // Get constraints. Will return the // names of all constraints. $constraints = $schema->constraints() // Get data about a single constraint. $constraint = $schema->constraint('author_id_idx') // Get indexes. Will return the // names of all indexes. $indexes = $schema->indexes() // Get data about a single index. $index = $schema->index('author_id_idx') ``` -------------------------------- ### Composer Install for GitHub Source Source: https://github.com/cakephp/docs/blob/5.x/docs/en/development/testing.md Composer command to install dependencies when using CakePHP source from GitHub. ```bash composer install ``` -------------------------------- ### Build Basic Controller/Action URL Source: https://github.com/cakephp/docs/blob/5.x/docs/en/views/helpers/url.md Use build to create URLs for controller actions. Pass an array with 'controller' and 'action' keys. ```php echo $this->Url->build([ 'controller' => 'Posts', 'action' => 'view', 'bar', ]); ``` -------------------------------- ### Get Plugin Config Path Source: https://github.com/cakephp/docs/blob/5.x/docs/en/core-libraries/plugin.md Use Plugin::configPath() to get the path to a plugin's configuration files. Pass the plugin name as a string argument. ```php $path = Plugin::configPath('DebugKit'); ``` -------------------------------- ### Get User Input with ConsoleIo::ask Source: https://github.com/cakephp/docs/blob/5.x/docs/en/console-commands/input-output.md Use the ask method to get arbitrary text input from the user. Provide a prompt and an optional default value. ```php $color = $io->ask('What color do you like?'); ``` -------------------------------- ### Controller Example Returning JSON Source: https://github.com/cakephp/docs/blob/5.x/docs/ja/development/testing.md A basic example of a CakePHP controller action that sets data and uses `viewBuilder()->setOption('serialize', ['marker'])` to return JSON. ```php class MarkersController extends AppController { public function initialize(): void { parent::initialize(); $this->loadComponent('RequestHandler'); } public function view($id) { $marker = $this->Markers->get($id); $this->set('marker', $marker); $this->viewBuilder()->setOption('serialize', ['marker']); } } ``` -------------------------------- ### Example Word Count Result Structure Source: https://github.com/cakephp/docs/blob/5.x/docs/en/orm/retrieving-data-and-resultsets.md This is an example of the associative array structure that the word count map-reduce operation might return, mapping words to their frequencies. ```json [ 'cakephp' => 100, 'awesome' => 39, 'impressive' => 57, 'outstanding' => 10, 'mind-blowing' => 83, ] ``` -------------------------------- ### Getting Help as XML Source: https://github.com/cakephp/docs/blob/5.x/docs/en/console-commands/option-parsers.md Details how to obtain machine-parseable help content in XML format by appending the `xml` option to the help request. ```APIDOC ## GET /shell/help?format=xml ### Description Retrieves help information for CakePHP shell commands in an XML format, suitable for automated tools. ### Method `cake [shell_name] --help xml` or `cake [shell_name] -h xml` ### Endpoint N/A (Command-line interface) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash cake bake --help xml ``` ### Response #### Success Response (200) An XML document containing the generated help, options, and arguments for the selected shell. #### Response Example ```xml bake fixture Generate fixtures for use with the test suite. You can use `bake fixture all` to bake all fixtures. Omitting all arguments and options will enter into an interactive mode. ``` ```