Welcome Guest, Not a member yet? Register   Sign In
CLI library : be able to print arrays or objects
#1

Hi,

Would it be possible to add the equivalent of print_r or var_dump to the CLI librayy ? 
Actually, it only allows strings as input and this will also permit to display arrays and objects.
Thank you,

Fred
Reply
#2

Use dd()
https://codeigniter4.github.io/CodeIgnit...ng.html#dd
or d()
https://codeigniter4.github.io/CodeIgnit...ing.html#d
Reply
#3

Thank you, I didn't know this one for CI ;-)
Reply
#4

(This post was last modified: 12-11-2023, 05:48 AM by Fred9176.)

I noted something strange : if I use print_r or d() between CLI:write commands, the result of these 2 commands are all written after all the CLI:write commands returns.

For example, the following code: 

PHP Code:
CLI::write('before');
print_r('print_r command');
d('d command');
CLI::write('after'); 



Will render :


Code:
before
sh: tput: not found
after
print_r command
┌──────────────────────────────────────────────────────────────────────────────┐
└──────────────────────────────────────────────────────────────────────────────┘
string (9) "d command"
════════════════════════════════════════════════════════════════════════════════
Called from .../modules/Electricite/Models/ReleveModel.php:37 [d()]

I created a custom library to add print_r et var_dump to CLI :

PHP Code:
<?php

namespace App\Libraries;

use 
CodeIgniter\CLI\CLI as BaseCLI;

class 
CLI extends BaseCLI
{

    /**
    * Outputs result of print_r to the cli on its own line.
    *
    * @return void
    */
    public static function print_r($data, ?string $foreground null, ?string $background null)
    {
        $toPrint print_r($dataTRUE);
        CLI::write($toPrint$foreground$background);
    }

    /**
    * Outputs result of vaar_dump to the cli on its own line.
    *
    * @return void
    */
    public static function var_dump($data, ?string $foreground null, ?string $background null)
    {
        ob_start();
        var_dump($data);
        $toPrint ob_get_contents();
        ob_end_clean();

        CLI::write($toPrint$foreground$background);
    }

Reply




Theme © iAndrew 2016 - Forum software by © MyBB