Welcome Guest, Not a member yet? Register   Sign In
  how to manage DB connections
Posted by: PaulC - 04-10-2025, 06:04 AM - Replies (4)

Hi If so how do  Team,
In my CI3 app I never worried about this because we autoloaded 'database' lib.
In CI4 it seems I now have to connect in my code - I have chosen the constructor of any Controller or Model where ever I need to access the database.
I am now aware that I could hit connection limits (currently 151 by default for mysql db)
A few (perhaps) obvious questions:
1) If I make a connection in a controller and the user session redirects to another controller will the $db persist for the session or do I open a second etc connection?
2) Should I check for an existing connection in each constructor and either proceed or open a new connection as appropriate? If so how please?
3) Another potential strategy would be to force a disconnect on completion of my db interation. If so how please?
4) I quite like the freeQuery() call. Is this recommended to optimise memory as lng as you don't need the cached result?
I have read the upgrade notes carefully but haven't found those nuggets yet.
Appreciate any thoughts and guidance.
TIA, Paul


Sorry typo in first line ...groan


Lightbulb CRUD Code Generator
Posted by: DeanE10 - 04-09-2025, 10:32 AM - Replies (3)

I know this is an off subject for many but thought I'd ask anyway.... I have a Scaffold/CRUD Gen that I have been working on specifically for myself. I started it a while back, found some that were cool and modeled after them a bit but it wasn't very modular and code updates kept breaking everything. The last one I found back in 2020 was good from Adel (https://github.com/Adel-Qusay/Codeignite...-generator) so I modeled mine over the years like this one. I just refreshed the code so it works great with PHP 8.2 and CI4 4.6. And, NO it is not a copy of Adels code aside from a few Token names Smile

Thoughts?
[Image: CI4-CRUD-Gen_2025-1.png]
[Image: CI4-CRUD-Gen_2025-2.png]
[Image: CI4-CRUD-Gen_2025-3.png]


  Adding variables passed by pagelinks
Posted by: cadgiru - 04-09-2025, 01:25 AM - Replies (1)

$pager->appends(['filter' => 'foo'])->links();
Is this a valid way to add data to pagelinks?


  CodeIgniter base_url Configuration Issue
Posted by: carolynrichard - 04-09-2025, 01:12 AM - No Replies

Hello,
I’ve been working with CodeIgniter for a while, and it's been great so far. However, I’m having trouble understanding how base_url works. For instance, I’ve set the base_url like this:

Code:
$config['base_url'] = 'http://Office-Inventory/';

But when I try to access http : // Office-Inventory/, I get a 404 Not Found error:

Code:
Not Found The requested URL was not found on this server. Apache/2.4.58 (Win64) OpenSSL/3.1.3 PHP/8.2.12 Server at dict-inventory Port 80

Interestingly, when I use http :// localhost:8000/, everything works as expected, and I can access all the controllers using base_url() or site_url(). I’m confused because I expected http://Office-Inventory/ to work as well. Can anyone explain why it gives a 404 error, but http : //localhost:8000/ works fine?


  Debugbar not showing up
Posted by: Mrtemp - 04-08-2025, 06:27 AM - Replies (7)

Hi,
i got this porject from a collegue who quit and did not leave and documentaiton on the project i tried using the debugbar to understand the code better but its not showing up at all even when doing all the configuraiton required this is the configuration and some reponse in the network tab from the browser
.htaccess

Code:
# Disable directory browsing
Options -Indexes

# ----------------------------------------------------------------------
# Rewrite engine
# ----------------------------------------------------------------------

# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On

# If you installed CodeIgniter in a subfolder, you will need to
# change the following line to match the subfolder you need.
# http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
# RewriteBase /

# Redirect Trailing Slashes...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

#Add New Redirects Here

# Checks to see if the user is attempting to access a valid file,
# such as an image or css document, if this isn't true it sends the
# request to the front controller, index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]

# Ensure Authorization header is passed along
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
ErrorDocument 404 index.php
</IfModule>

# Disable server signature start
ServerSignature Off
# Disable server signature end

<Files .env>
    Require all denied
</Files>

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE image/svg+xml
    AddOutputFilterByType DEFLATE application/x-font
    AddOutputFilterByType DEFLATE application/x-font-truetype
    AddOutputFilterByType DEFLATE application/x-font-ttf
    AddOutputFilterByType DEFLATE application/x-font-otf
    AddOutputFilterByType DEFLATE application/x-font-woff
    AddOutputFilterByType DEFLATE application/x-font-woff2
    AddOutputFilterByType DEFLATE application/x-font-opentype
    AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
    AddOutputFilterByType DEFLATE application/font-woff
    AddOutputFilterByType DEFLATE application/font-woff2
    AddOutputFilterByType DEFLATE font/ttf
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/eot
    AddOutputFilterByType DEFLATE font/woff
    AddOutputFilterByType DEFLATE font/woff2
    AddOutputFilterByType DEFLATE font/opentype
</IfModule>

<IfModule mod_expires.c>
  ExpiresActive On

# Images
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/gif "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/webp "access plus 1 year"
  ExpiresByType image/svg+xml "access plus 1 year"
  ExpiresByType image/x-icon "access plus 1 year"

  # Video
  ExpiresByType video/webm "access plus 1 year"
  ExpiresByType video/mp4 "access plus 1 year"
  ExpiresByType video/mpeg "access plus 1 year"

  # Fonts
  ExpiresByType font/ttf "access plus 1 year"
  ExpiresByType font/otf "access plus 1 year"
  ExpiresByType font/woff "access plus 1 year"
  ExpiresByType font/woff2 "access plus 1 year"
  ExpiresByType application/font-woff "access plus 1 year"

  # CSS, JavaScript
  ExpiresByType text/css "access plus 1 year"
  ExpiresByType text/javascript "access plus 1 year"
  ExpiresByType application/javascript "access plus 1 year"

  # Others
  ExpiresByType application/pdf "access plus 1 year"
  ExpiresByType image/vnd.microsoft.icon "access plus 1 year"
</IfModule>

PHP Code:
app/config/Filters.php

public array $aliases = [
        'csrf'          => CSRF::class,
        'toolbar'      => DebugToolbar::class,
        'honeypot'      => Honeypot::class,
        'invalidchars'  => InvalidChars::class,
        'secureheaders' => SecureHeaders::class,
        'cors'          => Cors::class,
        'forcehttps'    => ForceHTTPS::class,
        'pagecache'    => PageCache::class,
        'performance'  => PerformanceMetrics::class,
        'auth'          => \App\Filters\Auth::class,
    ];

    /**
    * List of special required filters.
    *
    * The filters listed here are special. They are applied before and after
    * other kinds of filters, and always applied even if a route does not exist.
    *
    * Filters set by default provide framework functionality. If removed,
    * those functions will no longer work.
    *
    * @see https://codeigniter.com/user_guide/incoming/filters.html#provided-filters
    *
    * @var array{before: list<string>, after: list<string>}
    */
    public array $required = [
        'before' => [
            'forcehttps'// Force Global Secure Requests
            //'pagecache',  // Web Page Caching
        ],
        'after' => [
            //'pagecache',  // Web Page Caching
            //'performance', // Performance Metrics
            'toolbar',    // Debug Toolbar
        ],
    ];

    /**
    * List of filter aliases that are always
    * applied before and after every request.
    *
    * @var array<string, array<string, array<string, string>>>|array<string, list<string>>
    */
    public array $globals = [
        'before' => [
            // 'honeypot',
            'csrf',
            // 'invalidchars',
        ],
        'after' => [
            // 'honeypot',
            // 'secureheaders',
        ],
    ]; 


.env
Code:
CI_ENVIRONMENT = development
#--------------------------------------------------------------------
# APP
#--------------------------------------------------------------------
app.baseURL = http://127.0.0.1/MDN3/
browser network tab
1/bootstrap.min.css 200 127.0.0.1 stylesheet
2/MDN3?debugbar_time=1744112539.451802 301 127.0.0.1 xhr / Redirect


  Calendar Library for CodeIgniter4
Posted by: SergioDaroca - 04-07-2025, 09:51 AM - No Replies

I just adapted the fantastic original CI_Calendar Library (as in codeigniter 1.7.2), for PHP 8.*, tested with love on codeigniter 4.6

https://github.com/SergioDaroca/Calendar...deIgniter4

(to be honest DeepSeek did it all in one pass)
I have tested it -in codeigniter 4.6, and it works as the original did.

If somebody has the time to review, test, document, so it could be included in the framework, or set out as a module, it would be awesome.
This library was one of the main reasons I got to use CodeIgniter the first time. It is so easy and powerful.
I included a little howto, hope it helps! Smile


  Using a sql alias within a model's find() function
Posted by: Pardner - 04-06-2025, 02:30 PM - Replies (3)

I have a table that containes both Engligh and Spanish translations. The Spanish translation is a bit of an afterthough... so I am looking for an easy way to implement a language change accross my sight. What I am doing now is performing a callback after a model's find() function to unset all the translated columns and return only the sessions language:
test_en ---> test
unset(test_en)
unset(test_es)

Is there a way to implement an alias in the beforeFind callback? Can I modify the find query to select 'test_'.$_SESSION['lang'] AS test

Essentually, I would like to not fetch both columns just to unset the ones I don't want.

Here is my test model I am trying to play with:


PHP Code:
<?php 
namespace App\Models;
use 
CodeIgniter\Model;
class 
TestModel extends Model
{
    protected $table      'tblzz';
    protected $primaryKey 'id';
    protected $useAutoIncrement true;
    protected $returnType    'array';
//TODO: $useSoftDeletes = true; causes ->find() to return null
    protected $useSoftDeletes false;
    protected $allowedFields = ['id',
                                'test_en',
                                'test_es',
                                'date'];
    // Callbacks
    protected $allowCallbacks true;
    protected $beforeInsert  = [];
    protected $afterInsert    = [];
    protected $beforeUpdate  = [];
    protected $afterUpdate    = [];
    protected $beforeFind    = ['pickLang'];
    protected $afterFind      = ['parseLang'];
    protected $beforeDelete  = [];
    protected $afterDelete    = [];
    
    
public function pickLang($data){
        // Can I modify the query here to alias column 'test_'.$_SESSION['lang'] AS test
    }
    public function parseLang($data){
        if(isset($data['data'])){
                $tmp false;
                if(isset($data['data']['id'])){
                    //only one row, add an additional dimension to array in prep foreach loop
                    $tmp['data'][0] = $data['data'];
                    $data $tmp;
                }
                
                
foreach($data['data'] as $key => $d) {
                    $test $d['test_'.$_SESSION['lang']];
                    unset($data['data'][$key]['test_en']);
                    unset($data['data'][$key]['test_es']);
                    $data['data'][$key]['test'] = $test;
                }
              
              
if($tmp){
                  //remove additional dimension if one was added
                  $data['data'] = $data['data'][0];
              }
              
          
}
          return $data;
    }


  How to add data when loading CI4 library
Posted by: PaulC - 04-05-2025, 04:27 AM - Replies (5)

Hi Team,
I have had to bite the upgrade bullet. Generally I find the docs excellent, but I have hit a small issue with upgrading a CI3 load->library call which includes an array of parameters
ie
            //Load library
            $config['upload_path'] = $upload_folder;
            $config['allowed_types'] = 'jpeg|jpg|png';
            $config['max_size'] = $max_size * 1024;
            $config['file_name'] = $col.'_'.$row; //Temp name
       
            $this->load->library('upload', $config);
            $this->load->library('image_lib');
I can find no help on this migration.
Can anyone point me in the right direction please or explain what I need to refactor perhaps?
TIA, Paul


  Nested arrays in parser with conditional rendering
Posted by: artursampaio - 04-02-2025, 01:05 PM - Replies (1)

Hi,

I´d like to apply a conditional rendering in a nested iterator:
Code:
{parent}
  {children}
    {if $child->someAttribute == "1"}
      HELLO!
    {endif}
  {children}
{/parent}

I tried to use a static index and it works, but would be necessary to know the current iterator index
Code:
{parent}
  {children}
    {if $parent[0]->children[0]->someAttribute == "1"}
      HELLO!
    {endif}
  {children}
{/parent}
If there was something like:
Code:
{if $parent[$parent_idx]->children[$children_idx]->someAttribute == "1"}

Is this possible? There is any workaround?
Thanks in advance!


  How to Write API Documentation That Developers Will Love
Posted by: InsiteFX - 04-02-2025, 06:26 AM - No Replies

How to Write API Documentation That Developers Will Love


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

Username
  

Password
  





Latest Threads
Table (view class) Row ID
by chenzen
2 hours ago
AbuseIPDB Module
by grimpirate
3 hours ago
curl + response body
by okatse
7 hours ago
tool bar not showing
by Luiz Marin
11 hours ago
Tool bar not showing
by Luiz Marin
Today, 04:28 AM
Heads up for users using ...
by davis.lasis
Yesterday, 12:54 PM
The Hidden Cost of “Innov...
by fcoder
Yesterday, 03:11 AM
Validation does not appea...
by grimpirate
07-01-2025, 01:55 PM
Block IP addresses of bad...
by grimpirate
07-01-2025, 01:47 PM
Override Router
by grimpirate
07-01-2025, 01:30 PM

Forum Statistics
» Members: 154,554
» Latest member: 69vn15dev
» Forum threads: 78,438
» Forum posts: 379,721

Full Statistics

Search Forums

(Advanced Search)


Theme © iAndrew 2016 - Forum software by © MyBB