CodeIgniter Forums
CLI library : be able to print arrays or objects - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Feature Requests (https://forum.codeigniter.com/forumdisplay.php?fid=29)
+--- Thread: CLI library : be able to print arrays or objects (/showthread.php?tid=88926)



CLI library : be able to print arrays or objects - Fred9176 - 12-04-2023

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


RE: CLI library : be able to print arrays or objects - kenjis - 12-04-2023

Use dd()
https://codeigniter4.github.io/CodeIgniter4/testing/debugging.html#dd
or d()
https://codeigniter4.github.io/CodeIgniter4/testing/debugging.html#d


RE: CLI library : be able to print arrays or objects - Fred9176 - 12-10-2023

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


RE: CLI library : be able to print arrays or objects - Fred9176 - 12-11-2023

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);
    }