### Install CodeIgniter Source: https://codeigniter.com/user_guide/guides/api/index.html Installs CodeIgniter using Composer and starts the development server. ```bash composer create-project codeigniter4/appstarter books-api cd books-api php spark serve ``` -------------------------------- ### Project Folder Structure Example Source: https://codeigniter.com/user_guide/installation/running.html Example of project folder structure for VirtualHost setup. ```tree apache2/ ├── myproject/ (Project Folder) │ └── public/ (DocumentRoot for myproject.local) └── htdocs/ ``` -------------------------------- ### Performing Setup Logic with mount() Source: https://codeigniter.com/user_guide/outgoing/view_cells.html Example of implementing a mount() method in a View Cell to perform setup logic before rendering. ```php posts = model('PostModel')->orderBy('created_at', 'DESC')->findAll(10); } } ``` -------------------------------- ### Initializing the Database Class Source: https://codeigniter.com/user_guide/database/examples.html Loads and initializes the database class based on configuration settings. ```php getStartTime(); ``` -------------------------------- ### Running Multiple Applications - Zip File Installation Structure Example Source: https://codeigniter.com/user_guide/general/managing_apps.html Example of a project directory structure when installing CodeIgniter from a Zip file for multiple applications. ```plaintext blog/ shop/ codeigniter4/system/ ``` -------------------------------- ### Test Class with Parent Setup Call Source: https://codeigniter.com/user_guide/testing/overview.html Example of a test class that correctly calls the parent setup method. ```php getServer('some_data'); ?> ``` ```php getServer(['SERVER_PROTOCOL', 'REQUEST_URI']); ?> ``` -------------------------------- ### Start FrankenPHP Server Source: https://codeigniter.com/user_guide/installation/running.html Command to start the FrankenPHP server. ```bash frankenphp run ``` -------------------------------- ### initialize() Method Example Source: https://codeigniter.com/user_guide/models/model.html An example of extending the `initialize()` method to perform additional setup, such as appending custom fields to the model's allowed fields. ```php allowedFields[] = 'middlename'; } } ``` -------------------------------- ### FileHandler Driver - Directory Setup Source: https://codeigniter.com/user_guide/libraries/sessions.html Example commands for creating and securing the session save directory for the FileHandler driver. ```bash mkdir //writable/sessions/ chmod 0700 //writable/sessions/ chown www-data //writable/sessions/ ``` -------------------------------- ### Set Development Mode Source: https://codeigniter.com/user_guide/guides/api/index.html Copies the environment file and enables development settings. ```bash cp env .env ``` -------------------------------- ### AppInfo Command Example Source: https://codeigniter.com/user_guide/cli/cli_commands.html An example of a command that displays PHP and CodeIgniter version information, along with path details. ```php addUri('https://example.com/feeds/daily_photo.jpg')->copy(true); ``` -------------------------------- ### Authentication Trait Example Source: https://codeigniter.com/user_guide/testing/overview.html Example of using a trait to consolidate setup logic for test cases, specifically for authentication. ```php createFakeUser(); $this->logInUser($user); } // ... } ``` ```php getNamespace('Math\\Auth')[0]; $publisher = new Publisher($source, APPPATH); try { // Add only the desired components $publisher->addPaths([ 'Controllers', 'Database/Migrations', 'Models', ])->merge(false); // Be careful not to overwrite anything } catch (Throwable $e) { $this->showError($e); return; } // If publication succeeded then update namespaces foreach ($publisher->getPublished() as $file) { // Replace the namespace $contents = file_get_contents($file); $contents = str_replace('namespace Math\\Auth', 'namespace ' . APP_NAMESPACE, $contents); file_put_contents($file, $contents); } } } ``` -------------------------------- ### make:scaffold Example Source: https://codeigniter.com/user_guide/cli/cli_generators.html Example command to scaffold a complete set of stock code for a 'user' resource. ```bash php spark make:scaffold user ``` -------------------------------- ### getGetPost Example Source: https://codeigniter.com/user_guide/incoming/incomingrequest.html Example of how to retrieve a field from both GET and POST streams, prioritizing GET. ```php getGetPost('field1'); ?> ``` -------------------------------- ### getUserAgent Example Source: https://codeigniter.com/user_guide/incoming/incomingrequest.html Example of how to get the User Agent instance. ```php getUserAgent(); ?> ``` -------------------------------- ### Run Migrations Source: https://codeigniter.com/user_guide/guides/api/database-setup.html Command to execute the database migrations. ```bash php spark migrate ``` -------------------------------- ### Making a GET Request Source: https://codeigniter.com/user_guide/libraries/curlrequest.html Example of making a GET request to an API endpoint with authentication. ```php request('GET', 'https://api.github.com/user', [ 'auth' => ['user', 'pass'], ]); ``` -------------------------------- ### Install App Starter Source: https://codeigniter.com/user_guide/installation/installing_composer.html Creates a new CodeIgniter 4 project using the app starter repository. ```bash composer create-project codeigniter4/appstarter project-root ``` -------------------------------- ### getPostGet Example Source: https://codeigniter.com/user_guide/incoming/incomingrequest.html Example of how to retrieve a field from both POST and GET streams, prioritizing POST. ```php getPostGet('field1'); ?> ``` -------------------------------- ### Instantiating a Library Source: https://codeigniter.com/user_guide/general/modules.html Example of how to instantiate a library using its fully-qualified class name. ```php getGet(['field1', 'field2']); ?> ``` -------------------------------- ### Install AppStarter using Composer Source: https://codeigniter.com/user_guide/guides/first-app/index.html Installs the CodeIgniter AppStarter package to create a new project folder named 'ci-news'. ```bash composer create-project codeigniter4/appstarter ci-news ``` -------------------------------- ### Retrieving All GET Data with Filter Source: https://codeigniter.com/user_guide/incoming/incomingrequest.html This example shows how to retrieve all GET parameters and apply a filter to each of them. ```php getGet(null, FILTER_SANITIZE_FULL_SPECIAL_CHARS); // returns all GET items with string sanitation ?> ``` -------------------------------- ### Filtering GET Data Source: https://codeigniter.com/user_guide/incoming/incomingrequest.html This example demonstrates how to retrieve a GET parameter and apply a filter to sanitize it. ```php getGet('some_data', FILTER_SANITIZE_FULL_SPECIAL_CHARS); ?> ``` -------------------------------- ### Retrieving GET Data Source: https://codeigniter.com/user_guide/incoming/incomingrequest.html This example shows how to retrieve a specific GET parameter. If the parameter does not exist, null is returned. ```php getGet('some_data'); ?> ``` -------------------------------- ### Host Source: https://codeigniter.com/user_guide/libraries/uri.html Demonstrates setting and getting the host of a URI. ```php getHost(); // www.example.com echo $uri->setHost('anotherexample.com')->getHost(); // anotherexample.com ``` -------------------------------- ### Path Source: https://codeigniter.com/user_guide/libraries/uri.html Demonstrates setting and getting the path of a URI. ```php getPath(); // '/some/path' echo $uri->setPath('/another/path')->getPath(); // '/another/path' ``` -------------------------------- ### Retrieving Multiple Filtered GET Parameters Source: https://codeigniter.com/user_guide/incoming/incomingrequest.html This example shows how to retrieve an array of specific GET parameters and apply a filter to them. ```php getGet(['field1', 'field2'], FILTER_SANITIZE_FULL_SPECIAL_CHARS); ?> ``` -------------------------------- ### Allowing Redirects Source: https://codeigniter.com/user_guide/libraries/curlrequest.html Example of enabling redirects for a GET request. ```php request('GET', 'http://example.com', ['allow_redirects' => true]); /* * Sets the following defaults: * 'max' => 5, // Maximum number of redirects to follow before stopping * 'strict' => true, // Ensure POST requests stay POST requests through redirects * 'protocols' => ['http', 'https'] // Restrict redirects to one or more protocols */ ``` -------------------------------- ### PHP Preload Configuration Example Source: https://codeigniter.com/user_guide/installation/deployment.html Example of a PHP preload script configuration, showing how to set the include path for CodeIgniter. ```php __DIR__ . '/system', // <== change this line to where CI is installed // ... ], ]; // ... } // ... ``` -------------------------------- ### GET Route with Parameters Source: https://codeigniter.com/user_guide/incoming/routing.html This example demonstrates how to define a GET route that passes parameters to the controller method. The first example shows a simple call to a list method, while the second shows passing numeric parameters. ```php list() $routes->get('users', 'Users::list'); // Calls $Users->list(1, 23) $routes->get('users/1/23', 'Users::list/1/23'); ``` -------------------------------- ### Disabling Redirects Source: https://codeigniter.com/user_guide/libraries/curlrequest.html Example of explicitly disabling redirects for a GET request. ```php request('GET', 'http://example.com', ['allow_redirects' => false]); ``` -------------------------------- ### Timer::start() Source: https://codeigniter.com/user_guide/testing/benchmark.html Starts a timer with a given name. ```php start('render view'); ``` -------------------------------- ### Retrieving Session Data using get() method Source: https://codeigniter.com/user_guide/libraries/sessions.html Example of retrieving a session item using the session object's get() method. ```php get('name'); ``` -------------------------------- ### Calling parent setUp() and tearDown() methods Source: https://codeigniter.com/user_guide/testing/database.html When overriding `setUp()` and `tearDown()` methods, it's crucial to call the parent methods to retain the functionality provided by `DatabaseTestTrait`. ```php get('/', 'Home::index'); ``` -------------------------------- ### Retrieving Headers Source: https://codeigniter.com/user_guide/libraries/curlrequest.html Examples of how to get specific headers or all headers from a Response object. ```php getHeaderLine('Content-Type'); // Get all headers foreach ($response->headers() as $name => $value) { echo $name . ': ' . $response->getHeaderLine($name) . "\n"; } ``` -------------------------------- ### CodeIgniter Version 3.x Configuration Example Source: https://codeigniter.com/user_guide/installation/upgrade_configuration.html Example of a configuration file in CodeIgniter 3.x. ```php getDuration(); ``` -------------------------------- ### Start Development Server Source: https://codeigniter.com/user_guide/guides/api/first-endpoint.html Command to start the CodeIgniter development server. ```bash php spark serve ``` -------------------------------- ### getFieldCount() Example Source: https://codeigniter.com/user_guide/database/results.html Demonstrates how to get the number of fields (columns) returned by a query. ```php query('SELECT * FROM my_table'); echo $query->getFieldCount(); ``` -------------------------------- ### config:check command output example Source: https://codeigniter.com/user_guide/general/configuration.html Example output of the config:check command for the Config\App instance. ```text Config\App#6 (12) ( public 'baseURL' -> string (22) "http://localhost:8080/" public 'allowedHostnames' -> array (0) [] public 'indexPage' -> string (9) "index.php" public 'uriProtocol' -> string (11) "REQUEST_URI" public 'defaultLocale' -> string (2) "en" public 'negotiateLocale' -> boolean false public 'supportedLocales' -> array (1) [ 0 => string (2) "en" ] public 'appTimezone' -> string (3) "UTC" public 'charset' -> string (5) "UTF-8" public 'forceGlobalSecureRequests' -> boolean false public 'proxyIPs' -> array (0) [] public 'CSPEnabled' -> boolean false ) Config Caching: Disabled ``` -------------------------------- ### GET Route to Default Controller Method Source: https://codeigniter.com/user_guide/incoming/routing.html This example shows a GET route where the URL segment 'journals' maps to the default index() method of the Blogs controller. ```php get('journals', 'Blogs'); ``` -------------------------------- ### getNumRows() Example Source: https://codeigniter.com/user_guide/database/results.html Illustrates how to get the total number of records (rows) returned by a query. ```php query('SELECT * FROM my_table'); echo $query->getNumRows(); ``` -------------------------------- ### Using Prefixes in .env File Source: https://codeigniter.com/user_guide/libraries/encryption.html Shows how to use 'hex2bin:' and 'base64:' prefixes in the .env file for encryption keys. ```ini // For hex2bin encryption.key = hex2bin: // or encryption.key = base64: ``` -------------------------------- ### Query Builder Insert Source: https://codeigniter.com/user_guide/database/examples.html Uses the Query Builder to insert data into a table. ```php $title, 'name' => $name, 'date' => $date, ]; $db->table('mytable')->insert($data); // Produces: INSERT INTO mytable (title, name, date) VALUES ('{$title}', '{$name}', '{$date}') ``` -------------------------------- ### Create Migrations Source: https://codeigniter.com/user_guide/guides/api/database-setup.html Commands to generate migration files for 'authors' and 'books' tables. ```bash php spark make:migration CreateAuthorsTable php spark make:migration CreateBooksTable ``` -------------------------------- ### Getting a Specific Row as a Custom Object Source: https://codeigniter.com/user_guide/database/results.html Example of fetching a specific row as an instance of a custom class. ```php query('SELECT * FROM users LIMIT 1;'); $row = $query->getRow(0, "App\Entities\User"::class); echo $row->name; // access attributes echo $row->reverse_name(); // or methods defined on the 'User' class ``` -------------------------------- ### Setting Up Database Table with Command Source: https://codeigniter.com/user_guide/libraries/sessions.html CLI commands to generate and run a session migration. ```bash php spark make:migration --session php spark migrate ``` -------------------------------- ### Query Builder Query Source: https://codeigniter.com/user_guide/database/examples.html Uses the Query Builder to retrieve all results from a specified table. ```php table('table_name')->get(); foreach ($query->getResult() as $row) { echo $row->title; } ``` -------------------------------- ### Loading a View Source: https://codeigniter.com/user_guide/general/modules.html Example of how to load a view using its class namespace. ```php query('YOUR QUERY'); foreach ($query->getResultArray() as $row) { echo $row['title']; echo $row['name']; echo $row['body']; } ``` -------------------------------- ### write_file() - Basic Usage Source: https://codeigniter.com/user_guide/helpers/filesystem_helper.html This example demonstrates the basic usage of the write_file() function to write data to a file. If the file does not exist, it will be created. ```php escape($title) . ', ' . $db->escape($name) . ')'; $db->query($sql); echo $db->affectedRows(); ``` -------------------------------- ### CLI Arguments Example Source: https://codeigniter.com/user_guide/cli/cli_commands.html Demonstrates how the $params array is populated based on CLI arguments. ```php get(); ``` -------------------------------- ### Loading a Helper Source: https://codeigniter.com/user_guide/general/modules.html Example of how to load a helper function using the `helper()` function. ```php query('SELECT name FROM my_table LIMIT 1'); $row = $query->getRow(); echo $row->name; ``` -------------------------------- ### Get Compiled Upsert Query Source: https://codeigniter.com/user_guide/database/query_builder.html Example of compiling an upsert query to SQL string without running it, using `getCompiledUpsert()`. ```php 'ahmadinejad@example.com', 'name' => 'Ahmadinejad', 'country' => 'Iran', ]; $sql = $builder->setData($data)->getCompiledUpsert(); echo $sql; /* MySQLi produces: INSERT INTO `db_user` (`country`, `email`, `name`) VALUES ('Iran','ahmadinejad@example.com','Ahmadinejad') ON DUPLICATE KEY UPDATE `country` = VALUES(`country`), `email` = VALUES(`email`), `name` = VALUES(`name`) */ ``` -------------------------------- ### table() Example Source: https://codeigniter.com/user_guide/cli/cli_library.html Provides an example of how to display data in a formatted table using the table() method. ```php | | +-----------+----------------+------+-------------------------------------+----------------+---------------+ ``` -------------------------------- ### Fragment Source: https://codeigniter.com/user_guide/libraries/uri.html Demonstrates setting and getting the fragment of a URI. ```php $uri = new \CodeIgniter\HTTP\URI('http://www.example.com/some/path#first-heading'); echo $uri->getFragment(); // 'first-heading' echo $uri->setFragment('second-heading')->getFragment(); // 'second-heading' ``` -------------------------------- ### Standard Query With Single Result (Array version) Source: https://codeigniter.com/user_guide/database/examples.html Executes a standard SQL query and retrieves a single result as an array. ```php query('SELECT name FROM my_table LIMIT 1'); $row = $query->getRowArray(); echo $row['name']; ``` -------------------------------- ### Install Previous Version Source: https://codeigniter.com/user_guide/installation/installing_composer.html Installs a specific previous version of the CodeIgniter 4 app starter. ```bash composer create-project codeigniter4/appstarter:4.4.8 project-root ``` -------------------------------- ### Instantiating a Model Source: https://codeigniter.com/user_guide/general/modules.html Example of how to instantiate a model using its fully-qualified class name. ```php query('SELECT name, title, email FROM my_table'); $results = $query->getResultArray(); foreach ($results as $row) { echo $row['title']; echo $row['name']; echo $row['email']; } ``` -------------------------------- ### Standard Query With Multiple Results (Object Version) Source: https://codeigniter.com/user_guide/database/examples.html Executes a standard SQL query and retrieves results as an array of objects. ```php query('SELECT name, title, email FROM my_table'); $results = $query->getResult(); foreach ($results as $row) { echo $row->title; echo $row->name; echo $row->email; } echo 'Total Results: ' . count($results); ``` -------------------------------- ### Route with Multiple HTTP Verbs Source: https://codeigniter.com/user_guide/incoming/routing.html This example demonstrates using the match() method to allow a route to respond to multiple HTTP verbs (GET and PUT in this case). ```php match(['GET', 'PUT'], 'products', 'Product::feature'); ``` -------------------------------- ### Toolbar Configuration Source: https://codeigniter.com/user_guide/testing/debugging.html Example of how to configure the Toolbar by specifying which collectors to include in the app/Config/Toolbar.php file. ```php options))); foreach ($this->options as $option => $description) { CLI::write(CLI::color($this->setPad($option, $length, 2, 2), 'green') . $description); } /* * Output will be: * -n Set migration namespace * -g Set database group * --all Set for all namespaces, will ignore (-n) option */ ``` -------------------------------- ### GET Route with Segment Placeholder Source: https://codeigniter.com/user_guide/incoming/routing.html This example uses a (:segment) placeholder to match any value in the second URL segment and pass it to the productLookup method of the Catalog controller. ```php get('product/(:segment)', 'Catalog::productLookup'); ```