Lazy as f isnt about dry but baf when creating chartjs

· darkterminal's blog


Hello Punk! I am again… Yes the Software Freestyle Engineer! Too handsome and stupid from the first time you think who am I.

What I want to share about the title above “Lazy as F! Isn’t About D.R.Y but B.A.F When Creating ChartJS”?

Let me tell to you…

What The D.R.Y? #

Yes! As you expect! Thank you very much…

What The B.A.F Mean? #

Boring As F! Thank you very much again. I think I am too handsome for doing the kinda stuff over and over in ChartJS! So, I creating component (yes, if you think kind of React-things) like using HTML. For efficiency:

 1<?php
 2// Filename: /home/darkterminal/workspace/fck-htmx/app/config/ChartJS.php
 3
 4namespace App\config\helpers;
 5
 6class ChartJS
 7{
 8    private $type;
 9    private $data;
10    private $options;
11
12    public function __construct($type, $customOptions = [])
13    {
14        $this->type = $type;
15        $this->data = [
16            'labels' => [],
17            'datasets' => []
18        ];
19
20        $defaultOptions = [
21            'responsive' => true,
22            'plugins' => [
23                'title' => [
24                    'display' => true,
25                    'text' => 'Chart.js ' . ucfirst($type) . ' Chart'
26                ]
27            ]
28        ];
29        $this->options = array_replace_recursive($defaultOptions, $customOptions);
30    }
31
32    public function addLabel($label)
33    {
34        $this->data['labels'][] = $label;
35        return $this;
36    }
37
38    public function addDataset($label, $data, $backgroundColor, $borderColor, $additionalOptions = [])
39    {
40        $dataset = [
41            'label' => $label,
42            'data' => $data,
43            'backgroundColor' => $backgroundColor,
44            'borderColor' => $borderColor
45        ];
46
47        $dataset = array_merge($dataset, $additionalOptions);
48
49        $this->data['datasets'][] = $dataset;
50        return $this;
51    }
52
53    public function setOptions($options)
54    {
55        $this->options = array_merge_recursive($this->options, $options);
56        return $this;
57    }
58
59    public function getChartConfig()
60    {
61        return [
62            'type' => $this->type,
63            'data' => $this->data,
64            'options' => $this->options
65        ];
66    }
67
68    public function create(array $chartConfig, string $canvasName = 'myChart')
69    {
70        $html = '<div class="w-full">
71                <canvas id="' . $canvasName . '"></canvas>
72            </div>
73            <script type="module">
74                import {
75                    Chart,
76                    registerables
77                } from \'https://cdn.jsdelivr.net/npm/chart.js@4.4.2/+esm\';
78                Chart.register(...registerables);
79                const ctx = document.getElementById(\'' . $canvasName . '\');
80
81                if (ctx) {
82                    new Chart(ctx, ' . json_encode($chartConfig) . ');
83                } else {
84                    console.error(\'Canvas element with ID: ' . $canvasName . ' not found.\');
85                }
86            </script>';
87
88        return $html;
89    }
90}
91

I am a simple man and to the point! So, I created this ChartJS Class to wrap up the boring stuff and avoid switching between PHP and JavaScript over and over again. You know what I mean, right? Just say “Yes!” please…

I am a Software Engineer specializing in freestyle development, building web applications using PHP and HTMX. Therefore, I need to focus on writing less JavaScript code and shifting my state mindset to the server.

The Class Usage #

Instead of writing a bunch of JSON, I just need to write in my own preferred language (it's not a language, some people say from the background). Yes, PHP! That's part of Hypermedia, so I write using it.

PHP Hypertext Preprocessor

 1<?php
 2// Filename: /home/darkterminal/workspace/fck-htmx/views/components/dashboard/partials/ritail.chart.php
 3
 4use App\config\helpers\ChartJS;
 5
 6$overrideOptions = [
 7    'responsive' => true,
 8    'plugins' => [
 9        'legend' => [
10            'display' => false
11        ],
12        'title' => [
13            'display' => false,
14            'text' => 'Ritail Chart'
15        ]
16    ]
17];
18
19$chartJS = new ChartJS('line', $overrideOptions);
20
21$chartConfig = $chartJS->addLabel('January')
22    ->addLabel('February')
23    ->addLabel('March')
24    ->addDataset('Dataset 1', [65, 59, 80], 'rgba(75, 192, 192, 0.2)', 'rgb(75, 192, 192)')
25    ->addDataset('Dataset 2', [28, 48, 40], 'rgba(54, 162, 235, 0.2)', 'rgb(54, 162, 235)')
26    ->setOptions([
27        'scales' => [
28            'y' => [
29                'beginAtZero' => true
30            ]
31        ],
32        'elements' => [
33            'line' => [
34                'tension' => 0.4
35            ]
36        ]
37    ])
38    ->getChartConfig();
39
40$chartHTML = $chartJS->create($chartConfig, 'ritailChart');
41
42echo $chartHTML;
43

Did you see that!?

That's it! You're welcome…