The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by MUHAMMAD HAZLAN SHAH BIN IDRIS, 2023-07-12 23:57:56

CI4

CRUD Module

Keywords: CI4,CodeIgniter

CODE IGNI BASIC T SETUP E & CR R UD MO4DULE


LIST OF AUTHORS I


PREFACE II


TABLE OF CONTENTS III


CodeIgniter 4 is an excellent PHP framework for web applications. It offers enhanced features and improved performance compared to its predecessor, CodeIgniter 3. With a focus on performance optimization, it delivers fast load times and reduced server resource usage, making it ideal for high-performance applications. CodeIgniter 4 provides a modular and flexible development environment, allowing for the creation of reusable modules and promoting code reusability, maintenance simplicity, and scalability. It comes with a comprehensive set of features such as a powerful routing system, database abstraction, session management, form validation, and security features, streamlining rapid application development. The framework adheres to modern coding practices, taking advantage of the latest PHP features and ensuring compatibility with PHP 7 and above. It promotes a clean and readable codebase, making collaboration and code maintenance easier over time. CodeIgniter 4 offers extensive documentation, tutorials, and a vibrant community for developers to access ample resources and receive support. Its excellent performance, flexibility, and feature set make it a popular choice for a wide range of web development projects. In summary, CodeIgniter 4 is an excellent, lightweight, and versatile PHP framework that empowers developers to build robust web applications with speed and ease. INTRODUCTION 1


Model: Handles data and business logic, interacts with the database, and performs data processing and validation. View: Represents the user interface, presents data to users, and handles visual elements using HTML, PHP, CSS, and JavaScript. Controller: Acts as a mediator, receives user requests, communicates with the Model for data operations, and selects and prepares the View for displaying the final output. User sends a request to a specific URL. The Controller handles the request and interacts with the relevant Model. The Controller prepares data and selects the appropriate View. The View receives data and generates the output for the user. CodeIgniter 4 follows the Model-View-Controller (MVC) pattern for web development. MVC divides the application into three parts: Model, View, and Controller. The flow of MVC in CodeIgniter 4: 1. 2. 3. 4. Using MVC in CodeIgniter 4 enhances code organization, reusability, and maintainability. It allows developers to work on different components independently, making the application easier to understand, test, and modify. MVC IN CI4 2


I L L U S T R AT I O N O F M V C Responsible for storing and retrieving data Maintenance of state Notification of Observers of change in state Responsible for rendering of model- UI User interaction Renders Listbox Control, Facilitates selection Responsible for responding to user input Instructing the Model to respond to the user input. Handles Listbox Selection event, sends information to Model 3


Visit the official Laragon website: https://laragon.org/. Go to the download section. Laragon provides two versions: Laragon (full) and Laragon Lite. Download Laragon (full) version. SOFTWARE INSTALLATION LARAGON Once the download is complete, locate the downloaded file and run the installer. The installer will guide you through the installation process. Click "OK" to proceed. 4


Select the installation location for Laragon. By default, it will be installed in C:\laragon, but you can choose a different directory if desired. Click "Next" to continue. Select whether you want to set Laragon to auto start, auto detect and create virtual hosts or not. By default, it will set all setting to true, but you can uncheck any setting if desired. Click "Next" to continue. SOFTWARE INSTALLATION 5


6 Review the installation settings and click "Install" to start the installation process. SOFTWARE INSTALLATION Laragon will now be installed on your system.


7 Once the installation is complete, you'll see a "Finish" button. Make sure the "Run Laragon" option is checked and click "Finish." SOFTWARE INSTALLATION Laragon will automatically create a default project folder called www inside the Laragon installation directory (C:\laragon\www). You can place your PHP projects in this folder to work with them. Laragon will launch, and you'll see its control panel. From the control panel, you can start/stop services like Apache, MySQL, and other installed components.


Download PostgreSQL: Visit the official PostgreSQL website at https://www.postgresql.org/download/ and choose the appropriate version for your operating system. SOFTWARE INSTALLATION POSTGRESQL If you are using windows, click on "Windows" button. Click on the "Win x86-64" button on the desired version. It will then download the PostgreSQL archive file. Click on the "zip archive" highlighted text. It will then forward to the Community download page. 8


DOWNLOAD FOLDER LARAGON FOLDER SOFTWARE INSTALLATION Once the download is complete, Locate the downloaded PostgreSQL archive file and extract it. You will have a folder named "pgsql" with this sub-folder. Copy the pqsql folder with all of its contents and paste it inside this path: C:\laragon\bin\postgresql. Create the "postgresql" folder if you don't have one. 9


SOFTWARE INSTALLATION Open Laragon and click "Start All" button. Laragon will show all the system that are running. Including PostgreSQL with its default port which is "5432". 10


Download Composer: Visit the official Composer website at https://getcomposer.org/ and click the "Download" button. It will redirect you to the composer download page. SOFTWARE INSTALLATION COMPOSER On the Download page, click on the highlighted word "Composer-Setup.exe" to download the latest composer version. Once the download is complete, locate the downloaded file and run the installer. 11


SOFTWARE INSTALLATION The installer will guide you through the installation process. Click "Next" to proceed. Click the "Browse" button and locate the "command-line PHP" that is already installed inside the Laragon folder 12


SOFTWARE INSTALLATION By default the path of the "command-line PHP" is C"\laragon\bin\php\php-(your php version)\php.exe. Make sure you tick the "Add this PHP to your path?" checkbox. Then proceed by clicking "Next" button. Once you click "Next" button, the installer will run a "command-line PHP" checking. Wait till it is complete. 13


SOFTWARE INSTALLATION After the checking is complete. Click "Next" button. The installer will ask you to review the setting that you have previously set. Once you make sure that it has the setting like the pictures below, click "Install" button. 14


SOFTWARE INSTALLATION The installer will download and install composer on your device, wait until the process is 100% complete. Once, the installation is complete, the installer will display some information. Click "Next" button to continue. 15


SOFTWARE INSTALLATION That's it! You have completely installed composer on your device. Tick the "view online documentation" checkbox if you want to view it. Then click ""Finish" button. 16


SOFTWARE INSTALLATION VISUAL STUDIO CODE (VS CODE) Visit the official Visual Studio Code website: https://code.visualstudio.com/. Click the "Download" button and the website will direct you to the Download page. Click the "Download" button for Windows if you are using Windows, or choose another download type that is appropriate for your operating system. 17


18 SOFTWARE INSTALLATION Once the download is complete, locate the downloaded file and run the installer. On the License Agreement windows click on "I accept the agreement" radio button. Then click "Next" button. Select the installation location for VS Code. You can choose a different directory if desired or can proceed with the default directory by clicking "Next" button.


19 SOFTWARE INSTALLATION On "Select Start Menu Folder" windows. Click "Next" button to continue. On the "Select Additional Tasks" screen, you can also choose to add "Open with Code" option to your right-click context menu (Windows). Then click "Next" to proceed.


20 SOFTWARE INSTALLATION Review the installation settings that have been make, Click "Install" button to proceed with the installation. The installer will start installing vs code on your device, wait for it to complete.


21 SOFTWARE INSTALLATION Once, the installation is completed. Tick on the "Launch Visual Studio Code" checkbox and click "Finish" button. VS Code will open automatically, and you can customize the theme to your preference.


22 SOFTWARE INSTALLATION On the left panel, click on the extensions icon to find and install any extensions.


SOFTWARE INSTALLATION Level up your VS Code with Extensions VS Code offers hundreds of extensions that can help you during your development. Here are some recommendation that can help you during your web development project. Auto Rename Tag Better Comments DotENV HTML SS Support Laravel Artisan Laravel Blade formatter Laravel Blade Snippets Laravel Blade Spacer Laravel Extra Intellisense Laravel Goto Laravel Snippets Live Sass Compiler Material Icon Theme (or any other icon theme of your choice) PHP Debug PHP Extension Pack PHP Intelephense PHP IntelliSense PHP Namespace Resolver Prettier - Code formatter 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 23


SOFTWARE INSTALLATION DBEAVER Download DBeaver: Visit the official DBeaver website at https://dbeaver.io/download/. Once the download is complete, locate the downloaded file and run the installer. Choose your preferences language and click "OK" button. On the download page, you'll see different distribution options based on your operating system. Choose the appropriate version for your system (Windows, macOS, Linux, or Solaris) and click on the corresponding download link. 24


25 SOFTWARE INSTALLATION Follow the on-screen instructions provided by the installer to start the installation process. Click "Next" button. Read the DBeaver license agreement and, if you agree, Click "I Agree" button to proceed.


26 SOFTWARE INSTALLATION The installer will ask you to choose which users to install DBeaver Community for. Click on the radio button based on your preference, whether to install it for all users or only for yourself. Then click the "Next" button to proceed. The installer may offer options to select additional components or features to install along with DBeaver. Review the options and select/unselect as per your preference. Click "Next" to proceed.


SOFTWARE INSTALLATION You may be prompted to choose the destination folder where DBeaver will be installed. The default location is usually fine, but you can specify a different folder if desired. Click "Next" or "Continue" to proceed. If you're installing DBeaver on Windows, you may be prompted to choose the Start Menu folder where the shortcuts will be placed. You can either accept the default folder or specify a custom folder. Click "Next" or "Continue" to proceed. 27


28 SOFTWARE INSTALLATION Wait for the installation process to complete. This may take a few moments. The installer will now install DBeaver and any selected components/features. Once the installation is complete, click on the "Finish" button.


29 CREATE CONNECTION & SCHEMA Open Laragon, then click "Start All" button. Make sure PostgreSQL is running. Open DBeaver, It will displays a splash screen, wait till it finish loading.


30 If the software prompted you to create a sample database, click "No" button. DBeaver will prompted you to connect to a database. Click on "PostgreSQL" icon then click "Next" button. CREATE CONNECTION & SCHEMA


31 Host : "localhost" Port : "5432" Database : "postgres" Username : "postgres" Password : "" On the connection settings windows, enter the necessary connection details: Then, click the "Finish" button to create the new connection. In the DBeaver main window, you will see the newly created PostgreSQL connection in the left sidebar under the "Database Navigator" section. CREATE CONNECTION & SCHEMA


32 If DBeaver prompted Driver settings windows, Click the "Download" button. This will download all the PostgreSQL driver files. Once the download is completed, you can see your postgres connection details in the left sidebar under the "Database Navigator" sectio. CREATE CONNECTION & SCHEMA


Right-click on the "Schemas" directory under the postgres connection and select "Create New Schema" from the context menu. 33 You will be prompted with a "Create schema" windows. Enter the schema name and select the owner of the schema as below: Click "OK" button to proceed. DBeaver will execute the necessary SQL commands to create the schema, and you will see the new schema listed under your PostgreSQL connection in the left sidebar. CREATE CONNECTION & SCHEMA


34 Congratulations! You have successfully created a PostgreSQL schema using DBeaver. You can now use DBeaver to manage and interact with the database, create tables, run queries, and perform various other database operations. CREATE CONNECTION & SCHEMA


35 CREATING CI4 PROJECT 2. Click the terminal button on the Laragon software. composer create-project codeigniter4/appstarter ci4_product 3. Write the following command into your terminal to create a ci4 project: 1. Open Laragon, then click "Start All" button. 4. Press the "Enter" button to execute the following commands and wait for the composer to download and install CI4. STEP 1: CREATE CODEIGNITER 4 PROJECT 5. After executing the commands and completing the installation process, you will have CI4 installed with a project named "ci4_product." 6. Write the following command into your terminal to change directory to the project folder: cd ci4_product 7. Write the following command into your terminal to open your ci4 project in vs code: *Note: If the command is not recognized by terminal you can open the project manually from vs code code . 8. Here you can see several file which the composer has installed for you as below:


36 CREATING CI4 PROJECT php spark serve 9. Write the following command into your terminal to run and test your CI4 application locally: 10. Your terminal will look like below: 11. Copy the host address and paste it on your browser. You will see codeigniter 4 welcome page as below:


37 STEP 2: DATABASE CONFIGURATION In the second step, we will make database configuration for the example database name, username, password, etc for our CRUD application of codeigniter 4. Copy the "env" file and rename it as ".env". So let’s open the .env file and fill in all details as below: #------------------------------------------------------------- # ENVIRONMENT #------------------------------------------------------------- CI_ENVIRONMENT = development #------------------------------------------------------------- # APP #------------------------------------------------------------- app.baseURL = 'http://localhost:8080' # If you have trouble with `.`, you could also use `_`. # app_baseURL = '' # app.forceGlobalSecureRequests = false # app.CSPEnabled = false #------------------------------------------------------------- # DATABASE #------------------------------------------------------------- database.default.hostname = localhost database.default.database = postgres database.default.username = postgres database.default.password = database.default.DBDriver = postgre database.default.DBPrefix = database.default.schema = ci4_product database.default.port = 5432 # database.tests.hostname = localhost # database.tests.database = ci4_test # database.tests.username = root # database.tests.password = root # database.tests.DBDriver = MySQLi # database.tests.DBPrefix = # database.tests.port = 3306 CREATING CI4 PROJECT


38 CREATING CI4 PROJECT Then, open the 'Database.php' file located in app>Config>Database.php and change the '$default' value as below: /** * The default database connection. */ public array $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'postgres', 'password' => '', 'database' => 'postgres', 'DBDriver' => 'postgre', 'schema' => 'ci4_product', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => true, 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 5432, ];


39 STEP 3: CREATE MIGRATION Migration is a set of instructions or scripts that describe how to transform the database schema from one version to another. It defines the operations required to create, modify, or delete tables, columns, indexes, and other database objects. Write the following command into your terminal to create a migration file: php spark migrate:create product Your terminal should look like this: Then, locate and open the file you have created in this file directory: app/Database/Migrations. Your migration file will look like this: CREATING CI4 PROJECT


40 Write down the following codes: public function up() { $this->forge->addField([ 'id' => [ 'type' => 'INT', 'constraint' => 11, 'unsigned' => TRUE, 'auto_increment' => TRUE ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => '255', ], 'content' => [ 'type' => 'TEXT' ], ]); $this->forge->addKey('id', TRUE); $this->forge->createTable('posts'); } CREATING CI4 PROJECT


41 After that, run the command below: php spark migrate The command line will create a table in your database based on your migration code. Your updated code will look like this: <?php namespace App\Database\Migrations; use CodeIgniter\Database\Migration; class Product extends Migration { public function up() { $this->forge->addField([ 'id' => [ 'type' => 'INT', 'constraint' => 11, 'unsigned' => TRUE, 'auto_increment' => TRUE ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => '255', ], 'content' => [ 'type' => 'TEXT' ], ]); $this->forge->addKey('id', TRUE); $this->forge->createTable('posts'); } public function down() { // } } CREATING CI4 PROJECT


42 CREATING CI4 PROJECT Your terminal will look like this: If you open your database, you can see 'migrations' and 'products' table under the 'ci4_product' Schemas.


43 CREATING CI4 PROJECT STEP 4: ADD MODEL php spark make:model ProductModel Models are classes that handle database operations. They connect to the database, perform CRUD operations (create, read, update, delete), and have built-in methods for querying and validating data. Models help organize and manage data in an application. Write down the following code to create a model for 'Product' table The command line above will create 'ProductModel.php' file in the 'app/Models' Once you hit 'Enter', Your terminal will look like this: On you project directory 'app/Models' you will have 'ProductModel.php'. Update your Model like this: <?php namespace App\Models; use CodeIgniter\Model; class ProductModel extends Model { protected $table = 'ci4_product.products'; protected $returnType = 'object'; protected $allowedFields = [ 'id', 'name', 'detail', 'created_at', 'updated_at' ]; }


CREATING CI4 PROJECT 44 STEP 5: ADD CONTROLLER php spark make:controller ProductController A controller acts as the intermediary between the model and the view. It handles user requests, processes data from the model, and determines which view to display. Controllers in CodeIgniter 4 help maintain separation of concerns and facilitate the implementation of the MVC (Model-View-Controller) pattern. Afterwards, locate to this file directory: app/Controllers/ProductController.php. Inside this file, we will create the CRUD (Create, Read, Update, Delete) operations. Write down the following code to create a controller public function index() { $productModel = new ProductModel(); $products = $productModel->paginate(5); $pager = $productModel->pager; $data = [ 'products' => $products, 'pager' => $pager ]; return view('product/index', $data); } This method is responsible for displaying a listing of the products. It retrieves the products from the ProductModel using pagination. The retrieved products and the pagination information are passed to the product/index view. 'index()' method: public function create() { return view('product/create'); } This method shows the form for creating a new product. It returns the product/create view. 'create()' method:


45 CREATING CI4 PROJECT public function store() { $productModel = new ProductModel(); $productModel->insert($this->request->getPost()); return redirect()->route('/')->with('success', 'Product created successfully.'); } This method stores a newly created product in the storage. It retrieves the data from the form submitted using '$this->request->getPost()'. The data is then inserted into the database using the 'insert()' method of the 'ProductModel'. After the product is created, it redirects back to the index page and displays a success message. 'store()' method: public function show($id) { $productModel = new ProductModel(); $product = $productModel->find($id); return view('product/show', ['product' => $product]); } This method displays the details of a specific product. It retrieves the product with the given ID from the 'ProductModel'. The retrieved product is passed to the 'product/show' view. show($id) method: public function edit($id) { $productModel = new ProductModel(); $product = $productModel->find($id); return view('product/edit', ['product' => $product]); } This method shows the form for editing a specific product. It retrieves the product with the given ID from the 'ProductModel'. The retrieved product is passed to the 'product/edit' view. 'edit($id)' method:


CREATING CI4 PROJECT 46 public function update($id) { $productModel = new ProductModel(); $data = [ 'name' => $this->request->getPost('name'), 'detail' => $this->request->getPost('detail'), ]; $productModel->update($id, $data); return redirect()->route('/')->with('success', 'Product updated successfully'); } This method updates the specified product in the storage. It retrieves the data from the form submitted using '$this->request->getPost()'. The data is then updated in the database using the 'update()' method of the 'ProductModel'. After the product is updated, it redirects back to the index page and displays a success message. 'update($id)' method: public function destroy($id) { $productModel = new ProductModel(); $product = $productModel->find($id); if (!$product) { return redirect()->route('/')->with('error', 'Product not found'); } $productModel->delete($id); return redirect()->route('/')->with('success', 'Product deleted successfully'); } This method removes the specified product from the storage. It first checks if the product exists in the database. If the product doesn't exist, it redirects back to the index page and displays an error message. If the product exists, it deletes the product from the database using the 'delete()' method of the 'ProductModel'. After the product is deleted, it redirects back to the index page and displays a success message. 'destroy($id)' method:


Click to View FlipBook Version