### Initialize and Check Throttler Source: https://github.com/codeigniter4/userguide/blob/master/docs/libraries/throttler.html Demonstrates how to get an instance of the Throttler service and perform a check. This example sets up a bucket allowing 60 actions per minute, effectively one action per second. ```php check($name, 60, MINUTE); ``` -------------------------------- ### Hello World Controller Example (Legacy Auto-Routing) Source: https://github.com/codeigniter4/userguide/blob/master/docs/incoming/controllers.html A basic 'Hello World' controller that works with CodeIgniter's legacy auto-routing. Ensure the controller file name and class name start with an uppercase letter. ```php start('render view'); ``` -------------------------------- ### Publish Remote URI Example Source: https://github.com/codeigniter4/userguide/blob/master/docs/libraries/publisher.html This example shows how to download a remote resource using `addUri()` and publish it to your project, enabling overwrites with `true`. ```php addUri('https://example.com/feeds/daily_photo.jpg')->copy(true); ``` -------------------------------- ### Example Route Output (Legacy) Source: https://github.com/codeigniter4/userguide/blob/master/docs/incoming/routing.html An example of the output from the 'php spark routes' command, showing route details. ```text +---------+---------+---------------+-------------------------------+----------------+---------------+ | Method | Route | Name | Handler | Before Filters | After Filters | +---------+---------+---------------+-------------------------------+----------------+---------------+ | GET | / | » | \App\Controllers\Home::index | | toolbar | | GET | feed | » | (Closure) | | toolbar | +---------+---------+---------------+-------------------------------+----------------+---------------+ ``` -------------------------------- ### Example Spark Command Source: https://github.com/codeigniter4/userguide/blob/master/docs/cli/cli_commands.html A basic example of a Spark command class. This command can be executed from the CLI. ```php 'The name to greet.' ]; public function run(array $params) { $name = $params['name'] ?? 'World'; // Output a message to the console $this->line("Hello, {$name}!"); } } ``` -------------------------------- ### AuthPublish Command Example Source: https://github.com/codeigniter4/userguide/blob/master/docs/libraries/publisher.html Example of a custom CLI command to publish authentication module components. ```APIDOC ## `auth:publish` Command ### Description This command allows users to publish the authentication module's components (Controllers, Migrations, Models) into their application. ### Usage ```bash php spark auth:publish ``` ### Example Implementation ```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); } } } ``` ``` -------------------------------- ### Example Language File Content Source: https://github.com/codeigniter4/userguide/blob/master/docs/outgoing/localization.html An example of a language file containing both simple and nested language strings. ```php 'You must submit an email address', 'errorURLMissing' => 'You must submit a URL', 'errorUsernameMissing' => 'You must submit a username', 'nested' => [ 'error' => [ 'message' => 'A specific error message', ], ], ]; ``` -------------------------------- ### Basic Feature Test Class Setup Source: https://github.com/codeigniter4/userguide/blob/master/docs/testing/feature.html Sets up a feature test class by using DatabaseTestTrait and FeatureTestTrait. Ensure parent setUp() and tearDown() are called if overridden. ```PHP myClassMethod(); } protected function tearDown(): void { parent::tearDown(); $this->anotherClassMethod(); } } ``` -------------------------------- ### Equivalent Fabricator Setup for Test Helper Source: https://github.com/codeigniter4/userguide/blob/master/docs/testing/fabricator.html This demonstrates the equivalent setup using the `Fabricator` class directly, which is what the `fake()` helper function abstracts. ```php use CodeIgniter\Test\Fabricator; $fabricator = new Fabricator('App\Models\UserModel'); $fabricator->setOverrides(['name' => 'Gerry']); $user = $fabricator->create(); ``` -------------------------------- ### Retrieve Limited Records with get() Source: https://github.com/codeigniter4/userguide/blob/master/docs/database/query_builder.html The get() method accepts limit and offset parameters to control the number of records returned and their starting position. ```php get(10, 20); /* * Executes: SELECT * FROM mytable LIMIT 20, 10 * (in MySQL. Other databases have slightly different syntax) */ ``` -------------------------------- ### CodeIgniter 3 Database Query Example Source: https://github.com/codeigniter4/userguide/blob/master/docs/installation/upgrade_database.html Example of a database query using CodeIgniter 3 syntax, demonstrating select, where, limit, and get methods. ```php $query = $this->db->select('title') ->where('id', $id) ->limit(10, 20) ->get('mytable'); ``` -------------------------------- ### Configure Database Connection Source: https://github.com/codeigniter4/userguide/blob/master/docs/guides/first-app/news_section.html Example database configuration settings for the .env file. Ensure these match your local database credentials. ```properties database.default.hostname = localhost database.default.database = ci4tutorial database.default.username = root database.default.password = root database.default.DBDriver = MySQLi ``` -------------------------------- ### Instantiate Configuration Object with `new` Source: https://github.com/codeigniter4/userguide/blob/master/docs/general/configuration.html Use the `new` keyword to manually create an instance of a configuration class. ```php getStartTime(); ``` -------------------------------- ### CodeIgniter 3 Migration Example Source: https://github.com/codeigniter4/userguide/blob/master/docs/installation/upgrade_migrations.html This is an example of a CodeIgniter 3 migration file for creating a 'blog' table. It uses sequential naming and the older CI_Migration class structure. ```php dbforge->add_field(array( 'blog_id' => array( 'type' => 'INT', 'constraint' => 5, 'unsigned' => true, 'auto_increment' => true, ), 'blog_title' => array( 'type' => 'VARCHAR', 'constraint' => '100', ), 'blog_description' => array( 'type' => 'TEXT', 'null' => true, ), )); $this->dbforge->add_key('blog_id', true); $this->dbforge->create_table('blog'); } public function down() { $this->dbforge->drop_table('blog'); } } ``` -------------------------------- ### Example `config:check` Output Source: https://github.com/codeigniter4/userguide/blob/master/docs/general/configuration.html This output shows the structure and current values of the `Config\App` instance, including properties, their types, and values. It also indicates whether Config Caching is enabled. ```text Config\App#6 ( 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 ``` -------------------------------- ### CodeIgniter 3 Controller Source: https://github.com/codeigniter4/userguide/blob/master/docs/installation/upgrade_validations.html Example controller in CodeIgniter 3 demonstrating form validation setup and execution. ```php load->helper(array('form', 'url')); $this->load->library('form_validation'); // Set validation rules if ($this->form_validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } } ``` -------------------------------- ### Defining a Route for a Controller Method Source: https://github.com/codeigniter4/userguide/blob/master/docs/incoming/controllers.html Example of manually defining a GET route for the 'index' method of the 'HelloWorld' controller using PSR-4 Autoloader conventions. ```php (\)*\ */ $routes->get('helloworld', '\App\Controllers\HelloWorld::index'); ``` -------------------------------- ### Get URI Segment by Index Source: https://github.com/codeigniter4/userguide/blob/master/docs/libraries/uri.html Shows how to access specific segments of a URI path, starting from index 1. It also illustrates conditional segment retrieval. ```php getSegment(1) \=== 'users') { echo $uri\->getSegment(2); } ``` -------------------------------- ### Instantiate Configuration File Source: https://github.com/codeigniter4/userguide/blob/master/docs/general/modules.html Create a new instance of a configuration file using its fully qualified class name. ```php $config = new \Acme\Blog\Config\Blog(); ``` -------------------------------- ### Install CodeIgniter 4 Project Source: https://github.com/codeigniter4/userguide/blob/master/docs/guides/api/index.html Use Composer to create a new CodeIgniter 4 project for your API. Navigate into the project directory and start the development server. ```bash composer create-project codeigniter4/appstarter books-api cd books-api php spark serve ``` -------------------------------- ### Create a Custom Cast Handler Source: https://github.com/codeigniter4/userguide/blob/master/docs/models/entities.html Define a custom cast handler class that extends CodeIgniter\Entity\Cast\BaseCast. This example shows a Base64 encoder/decoder. Implement get() for retrieving and set() for storing data. ```php addDirectory(APPPATH . 'Filters'); ``` -------------------------------- ### Map HTTP Verbs to Controller Methods Source: https://github.com/codeigniter4/userguide/blob/master/docs/guides/api/first-endpoint.html Illustrates how different HTTP verbs map to specific controller method names when using auto-routing. For example, GET requests map to getIndex(), POST to postIndex(), and DELETE to deleteIndex(). ```plaintext HTTP Verb Method Name `GET /api/ping` `POST /api/ping` `DELETE /api/ping` `getIndex()` `postIndex()` `deleteIndex()` ``` -------------------------------- ### Retrieve Combined GET and POST Streams Source: https://github.com/codeigniter4/userguide/blob/master/docs/incoming/incomingrequest.html Retrieve all combined GET and POST data. GET data is preferred in case of name conflicts. ```php $request->getGetPost(); ``` -------------------------------- ### Load a Library using Factories Source: https://github.com/codeigniter4/userguide/blob/master/docs/concepts/factories.html Example of loading a library using the Factories::library() method after configuring a custom path. ```php use CodeIgniter\Config\Factories; $someLib = Factories::library('SomeLib'); ``` -------------------------------- ### Retrieve Combined GET and POST Parameter Source: https://github.com/codeigniter4/userguide/blob/master/docs/incoming/incomingrequest.html Retrieve a specific parameter from both GET and POST streams, prioritizing GET data. Filtering can be applied. ```php $request->getGetPost('field1'); ``` ```php $request->getGetPost('field1', FILTER_SANITIZE_FULL_SPECIAL_CHARS); ``` -------------------------------- ### Create and Reconfigure Encryption Instance Source: https://github.com/codeigniter4/userguide/blob/master/docs/libraries/encryption.html Demonstrates how to create a new Encryption instance and reconfigure it with custom settings using a configuration object. ```php initialize($config); ``` ```php initialize(\[\'cipher\' \=> \'AES-256-CTR\'\], \$config); ``` -------------------------------- ### Initialize Database Class Source: https://github.com/codeigniter4/userguide/blob/master/docs/database/examples.html Shows how to initialize the database class. Ensure your database configuration is set up correctly in app/Config/Database.php. ```php $db = database_connect(); // Or if you have multiple connections defined $db = database_connect('group_one'); ``` -------------------------------- ### Start and Stop Timer with Global Function Source: https://github.com/codeigniter4/userguide/blob/master/docs/testing/benchmark.html The global `timer()` function provides a shorthand for starting and stopping timers. Call it once to start and again with the same name to stop. ```php // Start the timer timer('render view'); // Stop a running timer, // if one of this name has been started timer('render view'); ``` -------------------------------- ### Get Records using Query Builder Source: https://github.com/codeigniter4/userguide/blob/master/docs/installation/upgrade_database.html Replaces the CI3 `$this->db->get()` method when used with the Query Builder. The `get()` method is now called on the builder instance. ```php $builder->get(); ``` -------------------------------- ### Initialize Session with ArrayHandler for Testing Source: https://github.com/codeigniter4/userguide/blob/master/docs/testing/session_testing.html Demonstrates how to create a session instance using the ArrayHandler driver, suitable for testing environments. Requires loading session configuration. ```php getGet() ``` ### Response Returns an array of GET data. ``` -------------------------------- ### Getting GET then POST Data Source: https://github.com/codeigniter4/userguide/blob/master/docs/incoming/incomingrequest.html Checks `$_GET` first, then `$_POST` for data. ```APIDOC ## getGetPost() ### Description Checks `$_GET` first, then `$_POST` for data. ### Method `getGetPost()` ### Endpoint N/A (Method of a Request object) ### Parameters None ### Request Example ```php $request->getGetPost() ``` ### Response Returns data found first in `$_GET`, then `$_POST`. ``` -------------------------------- ### Method Chaining Example Source: https://github.com/codeigniter4/userguide/blob/master/docs/database/query_builder.html Demonstrates how to chain multiple query builder methods together for a concise query construction. ```php select('title') ->where('id', $id) ->limit(10, 20) ->get(); ``` -------------------------------- ### Getting POST then GET Data Source: https://github.com/codeigniter4/userguide/blob/master/docs/incoming/incomingrequest.html Checks `$_POST` first, then `$_GET` for data. ```APIDOC ## getPostGet() ### Description Checks `$_POST` first, then `$_GET` for data. ### Method `getPostGet()` ### Endpoint N/A (Method of a Request object) ### Parameters None ### Request Example ```php $request->getPostGet() ``` ### Response Returns data found first in `$_POST`, then `$_GET`. ``` -------------------------------- ### CodeIgniter 3 Model Example Source: https://github.com/codeigniter4/userguide/blob/master/docs/installation/upgrade_models.html This is an example of a model file in CodeIgniter 3. ```php $title, 'slug' => $slug, 'text' => $text, ); return $this->db->insert('news', $data); } } ``` -------------------------------- ### Initialize Session using Helper Source: https://github.com/codeigniter4/userguide/blob/master/docs/libraries/sessions.html The session() helper function provides a friendlier way to access the default session configuration without passing any options. ```php getGet('some_data'); ``` ```php getGet('some_data', FILTER_SANITIZE_FULL_SPECIAL_CHARS); ``` -------------------------------- ### Initializing a Model Source: https://github.com/codeigniter4/userguide/blob/master/docs/models/model.html Demonstrates extending the `initialize()` method to perform additional setup after the model's constructor. This is useful for appending custom fields or other configurations. ```php allowedFields[] = 'middlename'; } } ``` -------------------------------- ### Initialize Session using Service Source: https://github.com/codeigniter4/userguide/blob/master/docs/libraries/sessions.html Use the service() method to get an instance of the Session class, optionally passing configuration. The default configuration is used if no config is provided. ```php getGet('some_data'); ``` The method returns null if the item you are attempting to retrieve does not exist. The second optional parameter lets you run the data through the PHP’s filters. Pass in the desired filter type as the second parameter: ```php $request->getGet('some_data', FILTER_SANITIZE_FULL_SPECIAL_CHARS); ``` To return an array of all GET items call without any parameters. ``` -------------------------------- ### Instantiate Library Source: https://github.com/codeigniter4/userguide/blob/master/docs/general/modules.html Create a new instance of a library using its fully qualified class name. ```php $lib = new \Acme\Blog\Libraries\BlogLib(); ``` -------------------------------- ### Start Local Development Server on Custom Host Source: https://github.com/codeigniter4/userguide/blob/master/docs/installation/running.html Specify a custom host for the local development server using the --host CLI option. This is useful for running multiple sites or testing specific domain configurations. ```bash php spark serve --host example.dev ``` -------------------------------- ### CodeIgniter 4.x Image Manipulation Example Source: https://github.com/codeigniter4/userguide/blob/master/docs/installation/upgrade_images.html Example of using the Image Manipulation Class in CodeIgniter 4.x. ```php $image = service('image'); $image->withFile('/path/to/image.jpg') ->thumbnail(['width' => 75, 'height' => 50]) ->save('/path/to/new_image.jpg'); ``` -------------------------------- ### initialize() Source: https://github.com/codeigniter4/userguide/blob/master/docs/genindex.html Initializes the encryption library. ```APIDOC ## initialize() ### Description Initializes the encryption library. ### Method (Not specified in source) ### Endpoint (Not specified in source) ### Parameters (Not specified in source) ### Request Example (Not specified in source) ### Response (Not specified in source) ``` -------------------------------- ### Plugin with Key/Value Parameters Source: https://github.com/codeigniter4/userguide/blob/master/docs/outgoing/view_parser.html Illustrates how to pass parameters to a plugin using key/value pairs. Values with spaces should be quoted. ```html {+ foo bar=2 baz="x y" +} ``` -------------------------------- ### CodeIgniter 3.x Image Manipulation Example Source: https://github.com/codeigniter4/userguide/blob/master/docs/installation/upgrade_images.html Example of using the Image Manipulation Class in CodeIgniter 3.x. ```php $this->load->library('image_lib'); $config['image_library'] = 'gd2'; $config['source_image'] = '/path/to/image.jpg'; $config['create_thumb'] = TRUE; $config['new_image'] = '/path/to/new_image.jpg'; $config['maintain_ratio'] = TRUE; $config['width'] = 75; $config['height'] = 50; $this->image_lib->initialize($config); if (!$this->image_lib->resize()) { echo $this->image_lib->display_error(); } ``` -------------------------------- ### Get and Set URI Host Source: https://github.com/codeigniter4/userguide/blob/master/docs/libraries/uri.html Demonstrates how to retrieve the host from a URI object and how to set a new host. ```php getHost(); // www.example.com echo $uri\->setHost('anotherexample.com')\->getHost(); // anotherexample.com ``` -------------------------------- ### Distinguishing Resource and Presenter Routes Source: https://github.com/codeigniter4/userguide/blob/master/docs/incoming/restful.html Example showing how to define distinct routes for resource and presenter controllers to avoid conflicts. ```php resource('api/photo'); $routes->presenter('admin/photos'); ``` -------------------------------- ### Install PHPUnit with Composer Source: https://github.com/codeigniter4/userguide/blob/master/docs/testing/overview.html Use Composer to add PHPUnit as a development dependency to your project. This is the recommended installation method. ```bash composer require --dev phpunit/phpunit ``` -------------------------------- ### Get Temporary Filename Source: https://github.com/codeigniter4/userguide/blob/master/docs/libraries/uploaded_files.html Gets the full path of the temporary file created during the upload process using the `getTempName()` method. ```APIDOC ## Get Temporary Filename ### Description Gets the full path of the temporary file created during the upload process using the `getTempName()` method. ### Method ```php $file->getTempName() ``` ### Parameters None ### Response - string: The full path to the temporary file. ### Example ```php $tempfile = $file->getTempName(); ``` ``` -------------------------------- ### Configure VirtualHost for Application Source: https://github.com/codeigniter4/userguide/blob/master/docs/installation/running.html Set up a VirtualHost element in your Apache configuration to serve your application. ```apache DocumentRoot "/opt/lamp/apache2/myproject/public" ServerName myproject.local ErrorLog "logs/myproject-error_log" CustomLog "logs/myproject-access_log" common AllowOverride All Require all granted ``` -------------------------------- ### getGetPost() Method Source: https://github.com/codeigniter4/userguide/blob/master/docs/incoming/incomingrequest.html Combines GET and POST data, prioritizing GET values in case of conflicts. Supports filtering and flags. ```APIDOC ## getGetPost() ### Description Retrieves data from both GET and POST streams, prioritizing GET values if keys conflict. It allows fetching a specific variable or combined streams, with options for filtering and flags. ### Method `getGetPost(string $index = null, int $filter = null, int $flags = null)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Get a specific variable from GET or POST (GET preferred) $request->getGetPost('field1'); // Get all GET and POST data combined (GET preferred on conflict) $request->getGetPost(); // Get combined data with specific filtering $request->getGetPost(null, FILTER_SANITIZE_STRING); ``` ### Response #### Success Response (200) Returns `$_GET` and `$_POST` combined if no parameters specified (prefer GET value on conflict), otherwise looks for GET value, if nothing found looks for POST value, if no value found returns null. Return type: `array|bool|float|int|object|string|null` #### Response Example ```json { "field1": "get_value_or_post_value", "field2": "post_only_value" } ``` ``` -------------------------------- ### Install Specific Version of CodeIgniter App Starter Source: https://github.com/codeigniter4/userguide/blob/master/docs/installation/installing_composer.html To install a specific version of the CodeIgniter app starter, append the desired version number to the command. This is useful for testing or maintaining compatibility. ```bash composer create-project codeigniter4/appstarter:4.4.8 project-root ``` -------------------------------- ### getGet() Method Source: https://github.com/codeigniter4/userguide/blob/master/docs/incoming/incomingrequest.html Retrieves GET data, with options for filtering and flags. If the first parameter is null, it returns all GET data. ```APIDOC ## getGet() ### Description Retrieves GET data from the incoming request. It allows for specifying an index to fetch a specific variable, applying filters, and setting flags for sanitation. If the first parameter is null, all GET items are returned and passed through the specified filter. ### Method `getGet(string $index = null, int $filter = null, int $flags = null)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Get all GET data with default filtering $request->getGet(null); // Get all GET data with specific sanitation $request->getGet(null, FILTER_SANITIZE_FULL_SPECIAL_CHARS); // Get a specific GET variable with sanitation $request->getGet('user_id', FILTER_SANITIZE_NUMBER_INT); // Get multiple GET variables with specific filters and flags $request->getGet(['id', 'page'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); ``` ### Response #### Success Response (200) Returns `$_GET` if no parameters supplied, otherwise the GET value if found, or null if not. Return type: `array|bool|float|int|object|string|null` #### Response Example ```json { "search_term": "example query", "page": "2" } ``` ``` -------------------------------- ### Start Local Development Server with Specific PHP Version Source: https://github.com/codeigniter4/userguide/blob/master/docs/installation/running.html Use the --php CLI option to specify a particular PHP executable path for the local development server. This allows testing with different PHP versions. ```bash php spark serve --php /usr/bin/php7.6.5.4 ``` -------------------------------- ### Retrieve Specific GET Parameters Source: https://github.com/codeigniter4/userguide/blob/master/docs/incoming/incomingrequest.html Retrieve specific GET parameters by passing an array of keys. Filtering can also be applied. ```php $request->getGet(['field1', 'field2']); ``` ```php $request->getGet(['field1', 'field2'], FILTER_SANITIZE_FULL_SPECIAL_CHARS); ``` -------------------------------- ### CodeIgniter 3.x Controller Example Source: https://github.com/codeigniter4/userguide/blob/master/docs/installation/upgrade_controllers.html This is an example of a controller in CodeIgniter 3.x. It extends CI_Controller and uses echo to output a string. ```php getGet(null, FILTER_SANITIZE_FULL_SPECIAL_CHARS); ``` -------------------------------- ### Getting Variable Data (Legacy) Source: https://github.com/codeigniter4/userguide/blob/master/docs/incoming/incomingrequest.html Retrieves data from `$_REQUEST` (GET, POST, COOKIE). Use with caution as it's for backward compatibility. ```APIDOC ## getVar() ### Description Retrieves data from `$_REQUEST` (GET, POST, COOKIE). This method exists for backward compatibility and should not be used in new projects. It may lead to unexpected overrides if not used carefully, especially with POST data potentially being overridden by cookies. If the incoming request has a `Content-Type` header set to `application/json`, this method returns the JSON data instead of `$_REQUEST` data. ### Method `getVar()` ### Endpoint N/A (Method of a Request object) ### Parameters None ### Request Example ```php $request->getVar() ``` ### Response Returns data from `$_REQUEST` or JSON data if applicable. ```