Welcome Guest, Not a member yet? Register   Sign In
  Dependency Management in Custom Services
Posted by: campio97 - 03-21-2025, 07:07 AM - Replies (1)

Hello
If I create a custom service, is it considered good practice to load models and other libraries/services directly within the service itself?Or is it better to pass all these instances from the controller when calling the service?

For example, if I have a service that requires 6 models and 3 other services or libraries, should I pass them all through the constructor?
Thank you [Image: smile.png]


  unit test class with phpunit
Posted by: solmazbabakan - 03-21-2025, 04:50 AM - Replies (1)

for my codeigniter 3 project i have creating a unit test class with phpunit:
i have following test controller :


PHP Code:
<?php
require_once("C:\\My_PC\\Birim Test\\...\\application\\core\\MY_UserController.php"); 
require_once 
'C:\\My_PC\\Birim Test\\...\\config.php';
require_once 
'C:\\My_PC\\Birim Test\\...\\application\\tests\\bootstrap.php';

if (!
defined('BASE_URL')) {
    define('BASE_URL''https://...com/'); 
}
use 
PHPUnit\Framework\TestCase;

class 
UserControllerTest extends TestCase {
    protected $CI;

    protected function setUp(): void {
        // Manually load CodeIgniter instance
        $this->CI = &get_instance();
        
        
// Load required models and libraries
        $this->CI->load->model('user_model');
        $this->CI->load->library('unit_test');

        // Load the controller manually
        require_once APPPATH 'controllers/Profil.php';
        $this->controller = new Profil();
    }

    public function testSaveCommentSuccess() {
        // Mock input data
        $_GET['issue'] = 'profil__comment';
        $_GET['report_id'] = 4901; 
        $_GET
['comment'] = 'This is a test comment';

        // Mock the model method
        $this->CI->user_model $this->createMock('User_model');
        $this->CI->user_model->method('update_comment')->willReturn(true);

        // Capture the output
        ob_start();
        $this->controller->save_comment();
        $output ob_get_clean();

        // Assert the output
        $this->assertJsonStringEqualsJsonString(json_encode(['success' => true]), $output);
    }

    public function testSaveCommentFailure() {
        // Mock input data
        $_GET['issue'] = 'profil__comment';
        $_GET['report_id'] = 4901; 
        $_GET
['comment'] = 'This is a test comment';

        // Mock the model method
        $this->CI->user_model $this->createMock('User_model');
        $this->CI->user_model->method('update_comment')->willReturn(false);

        // Capture the output
        ob_start();
        $this->controller->save_comment();
        $output ob_get_clean();

        // Assert the output
        $this->assertJsonStringEqualsJsonString(json_encode(['success' => false]), $output);
    }


in bootstrap then i have:

PHP Code:
define('APPPATH''C:\\My_PC\\Birim Test\\...\\application\\');
define('ENVIRONMENT''testing');

// Include your main configuration file
require_once 'C:\\My_PC\\Birim Test\\...\\config.php'// Adjust the path as needed
require_once 'C:\\My_PC\\Birim Test\\...\\system\\core\\CodeIgniter.php'; 

// Define BASE_URL if not already defined
if (!defined('BASE_URL')) {
    define('BASE_URL''https://....com/'); 


when i ran on local in terminal using:

PHP Code:
vendor/bin/phpunit --bootstrap application/tests/bootstrap.php application/tests/UserControllerTest.php 

i get :


PHP Code:
No direct script access allowed 

how can i resolve that? any help?


  Shield remove deleted at to user
Posted by: pippuccio76 - 03-20-2025, 06:53 PM - Replies (3)

i i try to remove deleted at symply by :

Code:
      $data_to_update = [

        'deleted_at' => NULL,
      ];

      $users_model->update($id, $data_to_update);

But i receive There is no data to update, i control $id it'ok


  Debug Toolbar -> show whole SQL query on error
Posted by: petewulf1 - 03-19-2025, 01:13 PM - No Replies

Hey guys,
the toolbar is rather useless in its current state if a sql query error occurs. For example
-----------------------------------------------
CodeIgniter\Database\Exceptions\DatabaseException #1054
Unknown column 'a.status' in 'field list'
 ----------------------------------------------
One has to scroll down the call stack to manually find the code where the query was executed which is unnecessarily time consuming.
Instead, the last query should be printed on top to quickly identify the corresponding code.

Thanks!


  Installation & Setup on Windows IIS
Posted by: wolverine4277 - 03-19-2025, 12:20 PM - No Replies

First of all, if the topic should go in another subforum feel free to move it.
After a long time trying to run an application developed with CodeIgniter4 on a server with IIS and due to some difficulties I decided to write this kind of tutorial.
On Apache in a local environment the applications work immediately, but when making the move to IIS is not so easy (or at least that's what happened to me).
Everything I am going to describe is in addition to what is indicated in the Getting started guide.

We will need:

  • Enable the mod_rewrite extension
  • Import the .htaccess file of the project to generate a web.config file like this:
    PHP Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="Regla 1 importada" stopProcessing="true">
                        <match url="^(.*)$" ignoreCase="false" />
                        <action type="Rewrite" url="public/{R:1}" />
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </configuration> 

  • Import the .htaccess file of the public folder to generate a web.config file like this:
    PHP Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="Regla 1 importada-1" stopProcessing="true">
                        <match url="^" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                            <add input="{URL}" pattern="(.+)/$" ignoreCase="false" />
                        </conditions>
                        <action type="Redirect" url="{C:1}" redirectType="Permanent" />
                    </rule>
                    <rule name="Regla 2 importada" stopProcessing="true">
                        <match url="^" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{HTTPS}" pattern="^on$" ignoreCase="false" negate="true" />
                            <add input="{HTTP_HOST}" pattern="^www\.(.+)$" />
                        </conditions>
                        <action type="Redirect" url="http://{C:1}{URL}" redirectType="Permanent" />
                    </rule>
                    <rule name="Regla 3 importada" stopProcessing="true">
                        <match url="^([\s\S]*)$" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                        </conditions>
                        <action type="Rewrite" url="index.php/{R:1}" appendQueryString="true" />
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </configuration> 

  • Create a virtual directory pointing to the public folder of the project (for example, if the project is located in c:\inetpub\wwwroot\myproject then we must add the virtual directory myproject pointing to c:\inetpub\wwwroot\myproject\public)
    To do this we select the folder above the project folder, right click on the folder and select the option Add virtual directory and configure an alias (myproject) and the physical path c:\inetpub\wwwroot\myproject\public.
  • Configure the HTTP verbs that we are going to use since not all are enabled by default (PUT is not enabled by default and when testing it threw me error 500, without recording in any error log the reason).
    To do this we select the project folder, double click on Handler mappings, double click on the PHP version we are using, then click on the Request Restrictions button
  • In the verbs tab we select the option All verbs or we select the option One of the following verbs and separate them with comma (for example: GET, PUT).

I hope it helps you, it would have saved me a lot of time to know all this when uploading my application to a Windows server.
Regards.


Luego de un buen tiempo intentando hacer funcionar un aplicación desarrollada con CodeIgniter4 sobre un servidor con IIS y debido a algunas dificultades que se me presentaron, me decidí a escribir esta especie de tutorial.
Sobre Apache en un entorno local las aplicaciones funcionan inmediatamente, pero al hacer el pase a IIS no es tan sencillo (o por lo menos es lo que me ha sucedido a mi).
Todo lo que voy a describir es adicional a lo indicado en la guía Como empezar.

Vamos a necesitar:
  • Habilitar la extensión mod_rewrite
  • Importar el archivo .htaccess del proyecto para generar un archivo web.config similar a este:
    PHP Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="Regla 1 importada" stopProcessing="true">
                        <match url="^(.*)$" ignoreCase="false" />
                        <action type="Rewrite" url="public/{R:1}" />
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </configuration> 

  • Importar el archivo .htaccess de la carpeta public para generar un archivo web.config similar a este:
    PHP Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="Regla 1 importada-1" stopProcessing="true">
                        <match url="^" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                            <add input="{URL}" pattern="(.+)/$" ignoreCase="false" />
                        </conditions>
                        <action type="Redirect" url="{C:1}" redirectType="Permanent" />
                    </rule>
                    <rule name="Regla 2 importada" stopProcessing="true">
                        <match url="^" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{HTTPS}" pattern="^on$" ignoreCase="false" negate="true" />
                            <add input="{HTTP_HOST}" pattern="^www\.(.+)$" />
                        </conditions>
                        <action type="Redirect" url="http://{C:1}{URL}" redirectType="Permanent" />
                    </rule>
                    <rule name="Regla 3 importada" stopProcessing="true">
                        <match url="^([\s\S]*)$" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                        </conditions>
                        <action type="Rewrite" url="index.php/{R:1}" appendQueryString="true" />
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </configuration> 

  • Crear un directorio virtual apuntando a la carpeta public del proyecto (por ejemplo, si el proyecto se encuentra en c:\inetpub\wwwroot\myproject\ entonces debemos agregar el directorio virtual myproject apuntando a c:\inetpub\myproject\public).
    Para esto seleccionamos la carpeta superior a la del proyecto, hacemos clic con el botón derecho sobre la carpeta y seleccionamos la opción Agregar directorio virtual y configuramos un alias (myproject) y la ruta de acceso física c:\inetpub\wwwroot\myproject\public
  • Configurar los verbos HTTP que vamos a utilizar ya que no todos están habilitados por defecto (PUT no está habilitado por defecto y al hacer pruebas me arrojaba error 500, sin grabar en ningún log de errores el motivo).
    Para esto seleccionamos la carpeta del proyecto, hacemos doble clic en asignaciones del controlador, hacemos doble clic en la versión de PHP que estamos utilizando, luego clic en el botón Restricciones de solicitudes
  • En la pestaña verbos seleccionamos la opción Todos los verbos o seleccionamos la opción Uno de los siguientes verbos y los separamos con coma (por ejemplo: GET, PUT).

Espero les ayude, a mi me habría ahorrado un buen tiempo saber todo esto a la hora de subir mi aplicación a un servidor Windows.
Saludos.


  Sentry CodeIgniter4 SDK Integration
Posted by: campio97 - 03-19-2025, 03:38 AM - Replies (2)

Hello everyone,
I am exploring the possibility of integrating Sentry with CodeIgniter 4. Has anyone already developed this integration? If not, would anyone be interested in collaborating on creating a dedicated Sentry-CodeIgniter4 SDK?
For error logging, the basic Sentry-PHP SDK is sufficient, but when it comes to performance monitoring and tracing, a more integrated solution is necessary. CodeIgniter 4 already gathers all the essential data for performance and traces through its debug toolbar, which uses collectors (see: https://codeigniter4.github.io/userguide...gging.html). We could potentially leverage these collectors, making the development of the SDK relatively straightforward.
What are your thoughts on this? Looking forward to your feedback and any potential collaboration!
Best regards,

PS: I opened a feature request on sentry-php sdk github too: https://github.com/getsentry/sentry-php/issues/1811


  9 Clever Tailwind Code Snippets for Faster Development
Posted by: InsiteFX - 03-18-2025, 10:24 PM - Replies (1)

9 Clever Tailwind Code Snippets for Faster Development


  Problem with route on CodeIgniter API
Posted by: wolverine4277 - 03-18-2025, 06:26 AM - Replies (4)

Hi, I'm begining using APIs with CodeIgniter.
After create a new project, the endpoint using POST doesn't works ( POST http://localhost/lab/php/client/ do de same that GET http://localhost/lab/php/client/, return http code 200 and all de clients ).
Clearly I'm doing something wrong, but I don't realize the mistake I'm making.
Someone with more experience than me (I recently started with the API theme with CodeIgniter4) could help me.
Regards.
Sebastián
Step by step
Create a lab folder inside www
Inside the lab folder:

Code:
composer create-project codeigniter4/appstarter php
I get a structure like that:

Code:
www
└── lab/
    └── php/ (project folder)
        └── public/

Edit .env:

Code:
app.baseURL = 'http://localhost/lab/php/'


In this point if I open http://localhost/lab/php/ I see the list of files, if I open http://localhost/lab/php/public/ I see the welcome page.

After adding .htaccess file to project root with:

Code:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
<FilesMatch "^\.">
    Require all denied
</FilesMatch>


Code:
www
└── lab/
    └── php/ (project folder)
        ├── .htaccess
        └── public/

When I open http://localhost/lab/php/ I see the welcome page.
Now I add two controllers for do some testing (ClientController and ProductController)

PHP Code:
$routes->get('client''ClientController::index');
$routes->get('client/(:segment)''ClientController::show/$1');
$routes->post('client''ClientController::create'); 
$routes->put('client/(:segment)''ClientController::update/$1');
$routes->patch('client/(:segment)''ClientController::update/$1');
$routes->delete('client/(:segment)''ClientController::delete/$1'); 

After this i check one by one with Postman. The only one that doesn't works was POST.
POST http://localhost/lab/php/client/ do de same that GET http://localhost/lab/php/client/, return http code 200 and all de clients

I know that i can do something like this:
$routes->resource('client', ['controller' =>'ClientController']);

but after the problem i separate the routes to check one by one


  DateTime field validation
Posted by: serialkiller - 03-18-2025, 03:58 AM - Replies (2)

I'm trying to validate a dateTime field but I can't get it to work, is this not possible or am I doing something wrong?

PHP Code:
'myDateTime' => 'required|valid_date["Y-m-d H:i"]'


  RSS with CI 4.6
Posted by: cb21 - 03-17-2025, 11:25 AM - Replies (6)

Where can I find a simple example of RSS creation with CodeIgniter 4.6 I found example but it does not work cause old version. We should remove all 10 years old answers it is useless today


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Latest Threads
Why PHP is still worth le...
by InsiteFX
4 hours ago
Any user guid or video o...
by msnisha
Yesterday, 02:30 PM
MVC vs MVCS vs CodeIgnite...
by massimiliano1.mancini
Yesterday, 10:15 AM
Is hiring a digital marke...
by Markhenry123
Yesterday, 02:45 AM
my controller fails to fi...
by PaulC
Yesterday, 01:40 AM
My Library cannot see ses...
by InsiteFX
05-08-2025, 08:48 PM
update the framework to t...
by captain-sensible
05-08-2025, 12:14 PM
CodeIgniter Shield 1.0.0 ...
by Ayatorvi
05-08-2025, 06:06 AM
Update to 4.6.1
by serialkiller
05-07-2025, 11:58 AM
Can't create new database...
by paulbalandan
05-07-2025, 08:49 AM

Forum Statistics
» Members: 145,048
» Latest member: vn13888pro
» Forum threads: 78,382
» Forum posts: 379,421

Full Statistics

Search Forums

(Advanced Search)


Theme © iAndrew 2016 - Forum software by © MyBB