Jump to content

PHP Frameworks for state


Adamhumbug

Recommended Posts

Hi All,

I have been writing raw PHP for some time and have been enjoying it - i am an ethusiastic beginner but have built some cool stuff and write fairly regularly as a hobby.As

One thing that gets a little bit tiresome occasionally is:

I build a nice UI that submits to the database.  I then have to write a lot more code to also handle existing data.

So... i create an add user page that looks great, adds dynamic content and saves to the DB.  Then, when i want to edit that user, i have to rebuld what i have done to take into account that there may be a user that i am editing rather than creating a new.  This often involves a lot of new code and refactoring of what i have done.

Now i understand that that is probably the nature of the beast but i am wondering if i should be exploring some frameworks (maybe laravel) as a next step progression or wheter i should be looking to move into htmx or javascript and my front and back end.

As i said above, i am an amatuer and have never done this professionally so am not aware of any "standards" and would love some experienced feedback on my options.

 

TLDR;

I want a faster way of handling both new data and editing data when it comes to building UI.

I am thinking about what is next in my coding journey.

 

 

As always, thanks in advance.

 

Adam

Link to comment
Share on other sites

perhaps you have seen my suggested page layout posted in the forum? code for any page should be laid out in this general order -

  1. initialization
  2. post method form processing
  3. get method business logic - get/produce data needed to display the page
  4. html document

when editing existing data, you would test for a requested edit id $_GET input in the get method business logic, if the form has never been submitted, to query for and fetch the existing data to be edited. you would fetch the data into a common array variable that also holds a trimmed working copy of the form data that gets set inside the post method form processing. this common array variable being empty or not is how you determine if the form has never been submitted (requires at least one valid $_POST field in the form.)

by using a little conditional logic in the form code to control a hidden field value indicating which post action (create/update) to preform, a hidden field with any requested edit id, and switch/case logic in the post method form processing to control which form processing code to execute, you can (re)use the same code for creating new entries or updating existing data.

also, once you have more then 2-3 form fields you need to dynamically validate and process the data and dynamically produce the form fields by creating a defining array with the expected fields, along with their field/data type, select/checkbox/radio choices, validation rules, processing rules, and any other unique values that define each field. you would then loop over this defining data to validate, process, and produce the form fields, instead of writing out code for every field.

Link to comment
Share on other sites

Using a framework like Laravel or CodeIgniter will cut down on the boilerplate code you're creating, but you still need to code. So while in vanilla PHP you'll write the DB connection script once then include it in an object and use that to persist the data to the database, with a framework you'll still be doing the same basic thing. The only difference is that someone has already written the DB connection for you - you still need to assign the values to the columns and tell the framework to save the record.

Where frameworks really come in handy is convenience and convention. Most frameworks that I know of these days are OOP-based so they're using either PDO or MySQLi behind the scenes, and most will parse the insert/select queries you pass to them into prepared statements. This is obviously convenient because you don't have to specifically write that code. It's still very possible to screw it up and bypass it, but you kinda have to try to do it. The convention part is less obvious and arguably less ... good, I guess. Frameworks have their own dialect of PHP and it's not always easy to learn or keep track of. On top of that, there's a lot of magic some frameworks (cough cough ... Laravel) inject that can make it difficult at times to reason about the path the data takes through your system. Once you learn the dialect you can get things done quite quickly, but sometimes that dialect changes in an update and that can make life difficult. Again, Laravel was most notorious for just changing major things in minor updates but they've lately stopped doing that and the upgrade path is much easier and safer than it was just a few years ago. That having been said, some of the major updates can still be rather jarring.

I'm not a blind fan of Laravel, but I've been using it for about 5 years now almost exclusively and I've gotten used to it and find it enjoyable for the most part. It offers a lot by default and once you get used to the syntax, service layer, and some of the other magic involved it's possible to get a lot done quickly. I've also worked with and enjoyed CodeIgniter 4 but it offers less built-in functionality and magic out of the box (or at least it did at the time). Yii sucks in my experience and opinion, but YMMV.

Oh, and obviously there's a learning curve with a framework - regardless of which you choose.

Edited by maxxd
Link to comment
Share on other sites

For me, personally, I am not a fan of frameworks at all and mostly enjoy raw coding more. However, I have used CodeIgniter for a couple of projects and enjoyed it. Massive learning curve but got the results I was after. I still go back to and prefer raw coding.

What I have done is, I created an application and used the UI for future projects. So, for example, login, register, users etc, all from the same UI. All I would need to change is the colours or fonts? Saves me a lot of time and effort.

Link to comment
Share on other sites

Yeah, I had a fairly robust component library before I ended up at jobs that used or were moving to Laravel - it's a good way to go whether you're using a framework or not. And it's always possible to use packages as bits and pieces in your own home-grown PHP code. Symfony is modular and it's easy to use composer install to use the packages you're interested in. Same with some of the Laravel packages, though I think that's probably more difficult as there's a lot of inheritance in Laravel and that could cause some issues.

Link to comment
Share on other sites

Thanks all for the comments here.  I feel like there is no real reason to go diving into frameworks based on what you have said.  I think the best way forward is for me to learn some of the professional practices that will make life easier.

 

An example of this is:

I still dont know if i should be writing code like this:

 

<div class="container-fluid">
    <h2>Candidates Ordered by Average Rating</h2>
    <div class="accordion" id="candidateAccordion">
        <?php foreach ($candidateDetails as $index => $candidate): ?>
            <div class="accordion-item">
                <h2 class="accordion-header" id="heading<?= $index ?>">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse<?= $index ?>" aria-expanded="false" aria-controls="collapse<?= $index ?>">
                        <?= htmlspecialchars($candidate['firstName'] . ' ' . $candidate['lastName']) ?> - Average Rating: <?= number_format($candidate['avgRating'], 2) ?>
                    </button>
                </h2>
                <div id="collapse<?= $index ?>" class="accordion-collapse collapse" aria-labelledby="heading<?= $index ?>" data-bs-parent="#candidateAccordion">
                    <div class="accordion-body">
                        <h5>Ratings and Comments per Criteria</h5>
                        <?php if (!empty($candidate['criteriaData'])): ?>
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>Criteria</th>
                                        <th>Rating</th>
                                        <th>Max Score</th>
                                        <th>Comments</th>
                                        <th>Interviewer</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($candidate['criteriaData'] as $criteria): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($criteria['criteriaName']) ?></td>
                                            <td><?= htmlspecialchars($criteria['rating']) ?></td>
                                            <td><?= htmlspecialchars($criteria['maxScoreName']) ?></td>
                                            <td><?= nl2br(htmlspecialchars($criteria['comments'])) ?></td>
                                            <td><?= htmlspecialchars($criteria['interviewerFirstName'] . ' ' . $criteria['interviewerLastName']) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php else: ?>
                            <p>No ratings or comments available for this candidate.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

Which i think is really messy - but very clear to see where everything is coming from.

OR

The method that i user where i build most of the html in a php function and return in - like this:

 

function showHighestScoreSelect($pdo, $hidden, $selectedOption = 0)
{
    $sql = "SELECT id, name from highest_score";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $highestScores = $stmt->fetchAll();

    $dnone = $hidden ? "d-none" : "";

    $out = "<div class='col-6 highestScore $dnone'>
                <label class='form-label w-100'>Highest Score
                    <select name='highestScore[]' class='form-select labelledInput'>
                        <option value='0' selected disabled>Please Select...</option>";

    foreach ($highestScores as $highestScore) {
        $scoreId = htmlspecialchars($highestScore['id'], ENT_QUOTES, 'UTF-8');
        $scoreName = htmlspecialchars($highestScore['name'], ENT_QUOTES, 'UTF-8');

        if ($selectedOption == $highestScore['id']) {
            $out .= "<option value='$scoreId' selected>$scoreName</option>";
        } else {
            $out .= "<option value='$scoreId'>$scoreName</option>";
        }
    }

    $out .= "		
            </select>
        </label>
    </div>";
    return $out;
}

One is much easier to see everything at once and the second is tidier in my opinion.

As i have no professional path to follow i use the one that i like (the second one) and run with it - but it does annoy me that when looking to change things or finding issues, i am clicking through endless functions.

I dont know what the pro's do?

I think i am going to focus on getting better at the basic ways of working as a start and you guys will no doubt have a wealth of opinion and experience that i would be very greatful if you could impart.

Thanks as always!

Link to comment
Share on other sites

honestly, whenever you have a wealth of functions doing their deeds, essentially you have the makings of a class. Frameworks are class based anyway, so it would be wise for one to make the switch to classes or frameworks. Furthermore, the database problems that you have mentioned can be mitigated by initial design, which should take these matters into account when setting up such a system. Think, plan, design, double-check, think more, imagine scenarios you haven't yet thought about, then build a development version for testing. If you build a solid foundation, then the site/project will withstand various environmental changes. Otherwise, the site/project will collapse like a stick house in a collision with an f5 tornado. One could go out-of-business with a bad design. Design is probably a scientific study on its own. The subject of architecture is intense. You should follow the advice by the pros in this forum. Alot of prominent members are are, in fact, pros and they have been through the bad times as well as the good times. The pros here can save you alot of time and hassle. If it is recommended to use a framework, then you should probably start reading about the suggested framework(-s).

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.