Jump to content

Recommended Posts

Hi Phreaks, hope you all had a productive weekend. I've been contemplating something on my project that I'm not sure about and thought here would be a great place to get some other insights into it. I don't believe I need any code for this question.

It's a fairly common setup index.php has category links that lead to a page that lists all items in that category. Click on an item and you go to the page specific to it. So let's say index.php->item_categories.php->single_item.php.

I originally had 2 methods in the Item class handling this -> getItemByCategory() and getSingleItem() each item has a bunch of properties to it so I decided I wanted to try to put them into one get() method. Which would require an IF statement. My question is, and pardon me if this sounds naive, what would any of you suggest for the condition?

it would very basically be ->

if(the page is items_categories.php){
run this code
} elseif(the page is single_item.php){
run this code
}

Is the best option, like in the example, to actually make the condition which page it is? Or sending some sort of indicator via GET?

Is there a common convention that is used for this scenario that I'm not aware of?

Looking forward to reading your responses

Link to comment
https://forums.phpfreaks.com/topic/313733-thoughts-on-if-condition/
Share on other sites

First you don't need an 'elseif' just 'else' unless there is more to the 'if' than you posted. When you call the function simply pass a boolean depending on which code you want to execute.

if($condition){
run this code
else{
run this code
}

 

Another way of doing it is if you have a list of buttons on your index page then check for the value of the button coming from $_POST in the index logic and do a header command to jump the the appropriate page for that button.  Works for me.

//   we have a post button to check
if ($_POST{'btn'] == 'Do X')
    header("Location: DoX.php");
if ($_POST['btn'] .....
    header(....);

 

Thanks for all your replies, gave me a lot to think about and consider. I've been working on this since I posted this question.

This is what I did - since categories.php has a $_GET["cat_id"] and single_item.php has a $_GET["item_id"] I did the following ->

<?php

public function get($id) {
            $field = ""; 
            $type = "";
            if(Input::get("cat_id")) {

                //retrieve all posts in the category
                $field = "post_cat_id";
                $query = $this->_db->get(self::$_table, array($field, "=", $id));
                $this->_data = $query->all();
                $type = "cat";
            } elseif(Input::get("post_id")) {

                //retrieve single post
                $field = "id";
                $query = $this->_db->get(self::$_table, array($field, "=", $id));
                $this->_data = $query->all();  
                $type = "single";
            }
            
            if($type == "cat") { 
                if(!$this->exists()) {
                    echo $this->html($type);
                } else {
                    $counter = 0;
                    while($counter < count($this->data())) {
                        foreach($this->data() as $obj) {
                            $data = array("id" => $obj->id, "title" => $obj->title, "content" => $obj->content, "author" => $obj->author, "add_by" => $obj->add_by, "category" => $obj->post_category, "image" => $obj->post_image, "num_likes" => $obj->num_likes, "num_comments" => $obj->num_comments, "num_views" => $obj->num_views );

                            if(strlen($data["content"]) > 200) {
                                $data["content"] = substr($data["content"], 0, 200) . "...";
                            }
                            echo $this->html($type, $data);
                            $counter ++;
                        }
                    }
                }
            } elseif($type == "single") {

                foreach($this->_data as $obj) {
                    $data = array("id" => $obj->id, "title" => $obj->title, "content" => $obj->content, "author" => $obj->author, "add_by" => $obj->add_by, "category" => $obj->post_category, "image" => $obj->post_image, "num_likes" => $obj->num_likes, "num_comments" => $obj->num_comments, "num_views" => $obj->num_views, "tags" => $obj->tags, "post_cat_id" => $obj->post_cat_id );
                }
                echo $this->html($type, $data);
            }
        }

$this->html() is as follows ->

<?php
private function html($type, $data = []) {
            $html = "";
            if($type == "cat") {
                if(!empty($data)) {

                    if($data["author"] !== 'contributor') {
                        $credit_str = "<p class='post-author'>Written By <a href='#'>{$data['author']}</a>&nbsp;&nbsp;
                        <span class=''>Added By <a href='#'>{$data['add_by']}</a></span></p>";
                    } else {
                        $credit_str = "<p class='post-author'>Added By <a href='#'>{$data['add_by']}</a></p>";
                    }
                   
                    $html .= "
                                
                    <div class='single-blog-post featured-post col-lg-4 mb-30'>
                        <div class='post-thumb'>
                            <a href='single_post.php?post_id={$data['id']}&related={$data['category']}'><img src='img/posts/{$data['image']}' alt=''></a>
                        </div>
                        <div class='post-data'>
                            <a href='single_post.php?post_id={$data['id']}&related={$data['category']}' class=''>
                                <h6>{$data['title']}</h6>
                            </a>
                            <div class='post-meta'>
                                $credit_str
                                <p class='post-excerp'>{$data['content']}</p>
                                
                                <div class='d-flex align-items-center'>
                                    <a href='#' class='post-like'><img src='../assets/img/like.png' alt=''> <span>{$data['num_likes']}</span></a>
                                    <a href='#' class='post-comment'><img src='../assets/img/chat.png' alt=''> <span>{$data['num_comments']}</span></a>
                                    <a href='#' class='post-comment'><i class='fa fa-eye'></i><span>{$data['num_views']}</span></a>
                                </div>
                            </div>
                        </div>
                    </div>";
                } else {
                    $html = "<h2 class='text-center text-danger my-4'>There are no posts in this category</h2>";
                }

            } elseif($type == "single") {

                if($data['author'] !== 'contributor') {
                    $credit = $data['author'];
                } else {
                    $credit = $data['add_by'];
                }

                $tag_str = "";
                $tags = explode(",", $data['tags']);
                foreach($tags as $tag) {
                    $tag_str .= "<li><a href='tags.php?tag=$tag' class='btn bg-color-primary text-color-fourth mx-1'>$tag</a></li>";
                }

                $content = str_replace(["\r", "\n"], '', $data['content']);

                $html .= "
                <div class='single-blog-post featured-post single-post'>
                    <div class='post-thumb'>
                        <a href='#'><img src='img/posts/{$data['image']}' alt=''></a>
                    </div>
                    <div class='post-data'>
                        <a href='category_posts.php?cat_id={$data['post_cat_id']}' class='post-catagory'>{$data['category']}</a>
                        <a href='#' class='post-title'>
                            <h6>{$data['title']}</h6>
                        </a>
                        <div class='post-meta'>
                            <p class='post-author'>By <a href='#'>$credit</a></p>
                            <p>{$content}</p>
                            <div class='newspaper-post-like d-flex align-items-center justify-content-between'>
                                
                                <div class='newspaper-tags d-flex'>
                                    <span>Tags: </span>
                                    <ul class='d-flex'>
                                        $tag_str
                                    </ul>
                                </div>

                                
                                <div class='d-flex align-items-center post-like--comments'>
                                    <a href='#' class='post-like'><i class='fa fa-thumbs-up'></i><span>{$data['num_likes']}</span></a>
                                    <a href='#' class='post-comment'><i class='fa fa-comment'></i> <span>{$data['num_comments']}</span></a>
                                    <a href='#' class='post-comment'><i class='fa fa-eye'></i><span>{$data['num_views']}</span></a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

               // THE REST IS IRRELEVANT AND REDACTED TO SAVE SPACE //
                ";
            }
            return $html;
        }

It works well but I'd still certainly be open to any comments regarding the decision and it's implementation.

I used elseif{} because I'll probably be expanding on it, maybe, maybe not

I forgot to mention that I can see myself breaking up the get() method into 2 methods in the future

Edited by TechnoDiver
Forgot to mention
7 hours ago, requinix said:

Kinda sounds like you're saying that this if check would go in the Item class. That is not the case, right? You're talking about putting the code in some other file, right?

That ^ was a hint.

2 minutes ago, requinix said:

Kinda sounds like you're saying that this if check would go in the Item class. That is not the case, right? You're talking about putting the code in some other file, right?

I'm not 100 clear on what you're saying. Do you mean putting the if check at the top of the actual page and call individual methods based off of that check?

The Item class should be responsible solely for the logic of an item. It should not have anything to do with determining what webpage was accessed, nor should it do anything with creating HTML markup. Those are responsibilities for other code.

  • Like 1
8 hours ago, requinix said:

The Item class should be responsible solely for the logic of an item. It should not have anything to do with determining what webpage was accessed, nor should it do anything with creating HTML markup. Those are responsibilities for other code.

Yea, that becomes more clear the more experience I get. I've already made a separate HTML class, I'll work on repositioning the logic. I'm catching what you're throwing out there now. Thanks

27 minutes ago, TechnoDiver said:

Yea, that becomes more clear the more experience I get. I've already made a separate HTML class, I'll work on repositioning the logic. I'm catching what you're throwing out there now. Thanks

I personally like leaving the HTML on the page itself as I like doing HTML/CSS mock-ups then just adding to the PHP to the HTML.

For example -

<main>
    <?php foreach ($cms as $record) { ?>
    <article class="cms">
        <img class="article_image"
             src="<?php echo htmlspecialchars($record['image_path']); ?>" <?= getimagesize($record['image_path'])[3] ?>
             alt="article image">
        <h2><?= $record['heading'] ?></h2>
        <span class="author_style">Created by <?= $record['author'] ?> on
                    <time datetime="<?= htmlspecialchars(CMS::styleTime($record['date_added'])) ?>"><?= htmlspecialchars(CMS::styleDate($record['date_added'])) ?></time></span>
        <p><?= nl2br($record['content']) ?></p>
        <?php echo (isset($_SESSION['id'])) ? '<a class="editButton" href="edit.php?id= ' . urldecode($record['id']) . '">Record ' . urldecode($record['id']) . '</a>' : null; ?>
    </article>
    <?php }
    $url = 'index.php';
    echo $pagination->new_page_links($url);
    ?>
</main>

I have a Database Object class

An example (not the whole code) -

namespace Techshangri;

use mysql_xdevapi\Exception;
use PDO;
use PDOException;

class DatabaseObject // The Parent Class:
{
    static protected string $table = ""; // Overridden by the calling class:
    static protected array $db_columns = []; // Overridden by the calling class:
    static protected array $objects = [];
    static protected array $params = [];
    static protected $searchItem;
    static protected $searchValue;

    /*
     * Pagination static function/method to limit
     * the number of records per page. This is
     * useful for tables that contain a lot of
     * records (data).
    */
    public static function page($perPage, $offset, $loc = 'index'): array
    {
        $sql = 'SELECT * FROM ' . static::$table . ' WHERE page=:page ORDER BY date_added DESC LIMIT :perPage OFFSET :blogOffset';
        $stmt = Database::pdo()->prepare($sql); // Prepare the query:
        $stmt->execute(['perPage' => $perPage, 'blogOffset' => $offset, 'page' => $loc]); // Execute the query with the supplied data:
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // more code...

and I have a Children's class that is more specific:

Children's Class (CMS.php) - Example -

class CMS extends DatabaseObject
{
    protected static string $table = "cms"; // Table Name:
    static protected array $db_columns = ['id', 'user_id', 'thumb_path', 'image_path', 'Model', 'ExposureTime', 'Aperture', 'ISO', 'FocalLength', 'author', 'heading', 'content', 'data_updated', 'date_added'];
    public $id;
    public $user_id;
    public $page;
    public $thumb_path;
    public $image_path;
    public $Model;
    public $ExposureTime;
    public $Aperture;
    public $ISO;
    public $FocalLength;
    public $author;
    public $heading;
    public $content;
    public $date_updated;
    public $date_added;

    /*
     * Construct the data for the CMS
     */
    public function __construct($args = [])
    {
        //        $this->user_id = $args['user_id'] ?? null;
        //        $this->author = $args['author'] ?? null;
        //        $this->heading = $args['heading'] ?? null;
        //        $this->content = $args['content'] ?? null;
        //        $this->date_updated = $args['date_updated'] ?? null;
        //        $this->date_added = $args['date_added'] ?? null;


        // Caution: allows private/protected properties to be set
        foreach ($args as $k => $v) {
            if (property_exists($this, $k)) {
                $v = static::filterwords($v);
                $this->$k = $v;
                static::$params[$k] = $v;
                static::$objects[] = $v;
            }
        }
    } // End of construct method:

    public static function styleTime($prettyDate): string
    {
        try {
            $dateStylized = new DateTime($prettyDate, new DateTimeZone("America/Detroit"));
        } catch (Exception $e) {
        }

        return $dateStylized->format("Y-m-d H:i:s");
    }
    
    // more code...

I use Active Record Design Pattern as for what I do doesn't get too complex and besides I'm starting to like this pattern. However, if I was doing a really large website I would go more the route of Model-View-Controller pattern. Well, at least I think I would? Anyways, I getting off topic and my point is that after struggling with OOP for awhile, I found out by doing tutorials and looking at examples is to keep your methods and even you classes as short as possible, plus try to have meaning to them that is helpful to you as the coder. The real benefit now is that I can transfer these classes over to other projects (websites) with no problem and that is when I find out if I have written a class that could had been written better.  As I sometimes find myself getting a little carried away with a class or putting a method (or even the variables) in the wrong class. I always shoot myself when I do that when come to that realization. 🤣 Everyone codes differently, but that is my logic.

  • Like 1
12 hours ago, Strider64 said:

I personally like leaving the HTML on the page itself as I like doing HTML/CSS mock-ups then just adding to the PHP to the HTML

That's interesting. I've used that method in a few, very sparse situations.

I originally wrote and still do write my HTML and CSS beforehand in a static way (where all repeated elements are typed in) and after I get the layout right I delete all but one of the repetitive elements and then cut->paste the last one into the HTML loop. At the time it was the best way I could fathom doing it with so many repeating elements being looped through.

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.