Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Adding features to a dynamic pagination script

Featured Replies

Hi, I have a PHP array of all folders in a directory, and creating a list of divs from them all with a specified class.

I have this jQuery script (CodePen link) that just simply requires me to specify the class of what elements I want to paginate, as well as have a place holder element for the pager below. That works fine. No other things needed.

But as of right now, this is a very basic script where the pager numbers just keep adding up. What I want to add is the previous/next/first/last buttons as well as say a limit of 5 numbers shown.

How can I add this to the script or is there any scripts with this already, that work just as simply like this, just dynamically paginating content of a specified class without doing anything more? All I can seem to find are scripts requiring bootstrap, databases, editing the html to differ each item or putting the dynamic content into the javascript file.

Thanks, Jase

I don't know the javascript way, but if you want to paginate with php ...

<?php
// Pagination
$totallist = count($your_results); // Count how many in your array.
$pagination_url = "/your-base-page/";
$rowsperpage = 10; // How Many Per Page
$totalpages = ceil($totallist / $rowsperpage);
if(isset($_GET['page'])) {
	if(!is_numeric($_GET['page'])) { 
		// They put ?page=fish or something
	} else {
		$page = (int)$_GET['page'];
		if($page < 1) { $page = 1; } // Stops Page 0.
	}
} else {
	$page = 1; // It's not set so assume the first page.
}
$offset = ($page-1) * $rowsperpage; $result_start = ($page-1)*$rowsperpage+1; $result_end = $result_start+$rowsperpage-1;
if($result_end >= $totallist) { $result_end = $totallist; };
if($page > 1) { if($page > $totalpages) { 
	// The page number is higher than the total pages, I normally 301 to page one.
} }
?>

... output the html results ...

<?php foreach(array_slice($your_results, $offset, $rowsperpage) as $sa) { ?>
<div>Your list item e.g. <?php echo $sa['folder']; ?></div>
<?php } ?>

... then the footer if there is more than one page ...

<?php if($totalpages>=2) { ?>
<div>Page <b><?php echo $page; ?></b> of <b><?php echo $totalpages; ?></b></div>
<div>
<?php $range = 2; // Sets how many pages either side of current, so this would make prev 1, 2, 3 (selected), 4, 5 next
if($page > 1){ $prevpage = $page - 1; echo "<a href='" . $pagination_url . "'"; if($prevpage>= 2) { echo "?page=".$prevpage; }; echo "' rel='prev'>Prev</a>"; }
for($x = ($page - $range); $x < (($page + $range) + 1); $x++) {	if(($x > 0) && ($x <= $totalpages)) { if($x == $page){ echo "<span>".$x."</span>"; } else { echo "<a href='" . $pagination_url; if($x>= 2) { echo "?page=" . $x; } echo "' class='submit yk lr3'>".$x."</a>"; } } }
if($page != $totalpages) { $nextpage = $page + 1; echo "<a href='" . $pagination_url . "?page=" . $nextpage . "' rel='next'>Next</a>"; }
?>
</div>
<?php } ?>

Hope this helps as a fallback :)

  • Author
<?php
	
	// initial array containing the dirs
	    $dirs = glob('*/posts/*', GLOB_ONLYDIR);
	
	// new array with date as key
    	    $dirinfo_arr = [];
            foreach ($dirs as $cdir) {
	
		// read date from file
                    $dirinfo_str = file_get_contents("$cdir/includes/post-info.json");
            	    $dirinfo = json_decode($dirinfo_str, TRUE);
        
        	// add current directory to the info array
        	    $dirinfo['dir'] = $cdir;
        	// add current dir to new array where date is the key
        	    $dirinfo_arr[$dirinfo['Arraysortdate']] = $dirinfo;
    	}
    	// now we sort the new array
    	    krsort($dirinfo_arr);

	    foreach($dirinfo_arr as $key=>$dir) {  // getting current dir from new array
	    	$dirpath = $dir['dir'];
?>

	
    	<div class="paragraph blog-menu-item paging-menu-item">
    	     <img class="blog-img lazy-load lazy-hide" data-src="<?=$dirpath?>/images/main.jpg"/>
    	     <noscript>
    	     	<img class="blog-img" src="<?=$dirpath?>/images/main.jpg"/>
    	     </noscript><br><br>
    	     
             <a href="<?=$dirpath?>">
             	<h1><?php include("$dirpath/includes/title.php");?></h1>
             </a><br>
             
             <span class="blog-date">
             	<strong>Date Published:</strong> <?php include("$dirpath/includes/date.php");?>
             </span><br><br>
             
             <span>
             	<?php include("$dirpath/includes/post-summary.php");?><br><br>
             	<a href="<?=$dirpath?>" style="color:darkred">Continue reading ></a><br><br>
             </span>
    	</div>
    	
<?php
};
?>

This is my PHP script for doing my menu, where $dirpath is the final variable for each array item.

Would I change $your_results to $dirpath and if I want the curent page as the base page, I assume I can just put "index.php" meaning as the index.php in the current folder?

Regarding the second part, I assume I take the echo $sa['folder'] and to add that in the way I have been using $dirpath as in my original script, assign another variable to that echo so I just am then able to do the same like this?

<?php foreach(array_slice($dirpath, $offset, $rowsperpage) as $sa) { 
    $dirpaginpath = echo $sa['folder'];
    ?>

        <div class="paragraph blog-menu-item paging-menu-item">
             <img class="blog-img lazy-load lazy-hide" data-src="<?=$dirpaginated?>/images/main.jpg"/>
             <noscript>
                 <img class="blog-img" src="<?=$dirpaginpath?>/images/main.jpg"/>
             </noscript><br><br>
             
             <a href="<?=$dirpaginpath?>">
                 <h1><?php include("$dirpath/includes/title.php");?></h1>
             </a><br>
             
             <span class="blog-date">
                 <strong>Date Published:</strong> <?php include("$dirpaginpath/includes/date.php");?>
             </span><br><br>
             
             <span>
                 <?php include("$dirpaginpath/includes/post-summary.php");?><br><br>
                 <a href="<?=$dirpaginpath?>" style="color:darkred">Continue reading ></a><br><br>
             </span>
        </div>

<?php } ?>

And then finally I take it that the last part is the PHP for the pager menu?

Edit, seems that it doesn't like this throwing up that the array slice expects an array so using $dirinfo_arr with the slice outside of the bottom foreach seems more correct as it doesn't through up the error, but how do I handle the ['folder'] and ['dir'] with this? Changed back my html to have $dirpath like previously as I assume I go back using that now.

Btw if you need to read up my thread where I built this script to get an understanding if your lost, here's the thread on Web Developer.

Also, if a mod wants to move this to server side forum, feel free as I did mean to do javascript but if php will work then definitely doing that instead.

Edited by jwbjnwolf

1 hour ago, jwbjnwolf said:

Would I change $your_results to $dirpath and if I want the curent page as the base page, I assume I can just put "index.php" meaning as the index.php in the current folder?

No, in your example $your_results would be $dirinfo_arr as this is the array you're using for output. Just trying to get my head around what you're trying to do. So this array ...

$dirs = glob('*/posts/*', GLOB_ONLYDIR);

... is just a single dimension array of directories, e.g. "/foldername/"? And the following ...

$dirinfo_str = file_get_contents("$cdir/includes/post-info.json");
$dirinfo = json_decode($dirinfo_str, TRUE);

... is making a multidimensional array of information from the post-info.json, which you push into the $dirinfo_arr. If so what are the keys when you use the following?

<?php foreach($dirinfo_arr as $row) { print_r(array_values($row)); } ?>

... an visual example of this multidimensional would be ...

<?php 
$dirinfo_arr = array(
array('name' => "Something", 'dir' => "/something/", 'date' => "2018-07-09"),
array('name' => "Something Else", 'dir' => "/wibble/", 'date' => "2018-07-01")
);
foreach($dirinfo_arr as $row) { print_r(array_values($row)); }
?>

... so if we loop through this array we can use those keys ...

<?php foreach($dirinfo_arr as $sa) { ?>
<ul>
  <li><?php echo $sa['name']; ?></li>
  <li><a href="<?php echo $sa['dir']; ?>"><?php echo $sa['dir']; ?></a></li>
  <li>Modified: <?php echo date('jS F Y', strtotime($sa['date'])); ?></li>
</ul>
<?php } ?>

... all the array_slice($dirinfo_arr, $offset, $rowsperpage) does is limit the results to the required set for pagination. With regards to the $pagination_url = "/your-base-page/"  you could set this to empty if you want, the reason I use it is to keep the pagination urls clean and also can be combined to use for canonical tags.

  • Author

Right I've included just two results for ease of understanding, along with the post-info.json contents for each.

1:

print_r result:

Array ( [0] => 2018-05-03 [1] => Array ( [0] => May 2018 ) [2] => Array ( [0] => Tutorials ) [3] => tech/posts/test2 ) 

Contents of json file:

{ "Arraysortdate": "2018-05-03",
  "Month": ["May 2018"],
  "Category": ["Tutorials"]
}

2:

print_r result

Array ( [0] => 2017-04-03 [1] => Array ( [0] => April 2017 ) [2] => Array ( [0] => Attention [1] => Friendships [2] => Love [3] => Love & Hate [4] => Pressure ) [3] => staystrong/posts/test-blog-post ) 

Contents of json file:

{
    "Arraysortdate": "2017-04-03",
    "Month": ["April 2017"],
    "Category": [
    		"Attention",
    		"Friendships", 
    		"Love", 
    		"Love & Hate", 
    		"Pressure"
    		]
}

This script is just taking the value of Arraysortdate to order the posts by date in the menu.

But if I also want to filter posts to only a certain category/month, I take the title of the current category/month page that the menu is on, and use in_array to only include posts if the value of either Month or Category matches the page title,, which is used as key.

// get current page title from file
	$pagetitle = file_get_contents("includes/title.php");

// before cycling through $dirinfo_arr for output
    	if(!in_array($pagetitle, $dirinfo['Month']) && !in_array($pagetitle, $dirinfo['Category'])) {
    		continue;
    }

This is done before this part of the script:

// add current dir to new array where date is the key
	$dirinfo_arr[$dirinfo['Arraysortdate']] = $dirinfo;  
   }

 

Edited by jwbjnwolf

Hmm, looks like it's getting a bit messy, even reading the other thread, might be easier to form one slick well named multidimensional array.

<?php
// initial array containing the dirs
$dirs = glob('*/posts/*', GLOB_ONLYDIR);
	
// new array with date as key
$dirinfo_arr = array();
foreach ($dirs as $cdir) {
  // read date from file
  $dirinfo_str = file_get_contents($cdir."/includes/post-info.json");
  $dirinfo = json_decode($dirinfo_str, TRUE);
  foreach($dirinfo as $dr) {
    $tmp_month = $dr['Month']; $tmp_category = $dr['Category']; $tmp_sortdate = $dr['Arraysortdate'];
  }
  $tmp_title = file_get_contents($cdir."/includes/title.php"); // If that's where the title is?
  $new_row = array('Arraysortdate' => $tmp_sortdate, 'Month' => $tmp_month, 'Category' => $tmp_category, 'Title' => $tmp_title, 'dir' => $cdir);
  $dirinfo_arr[] = $new_row;
}
// now we sort the new array
foreach($dirinfo_arr as $key => $row) {
  $sdate[$key]  = $row['Arraysortdate'];
  // Could also sort by others too.
  $stitle[$key]  = $row['Title'];
}
array_multisort($sdate, SORT_ASC, $stitle, SORT_ASC, $dirinfo_arr);
?>

Once you have one well formed array the rest is gravy :)

  • Author

Spent a while actually getting a better understanding of what you originally sent. So ['folder'] and ['dir'] is the same thing pretty much, so all I needed to do actually was simply replace 

foreach($dirinfo_arr as $key=>$dir) {
   	$dirpath = $dir['dir'];

with

foreach(array_slice($dirinfo_arr, $offset, $rowsperpage) as $dir) {
	$dirpath = $dir['dir'];

That works flawlessly.

Now regarding the pager navigation.. The 1st page link keeps reloading the current page not page=1, and the prev button doesn't load the last page either. The only difference I've done with your code for the pagination is as you said, make the pagination_url empty so that it's /?page=# instead of /index.php?page=#.

Also, regarding the page titles, the logic there I am doing is for on say a monthly archive page such as 2017/04, which has a title "April 2017". I am taking this title to use as key to only include posts with a matching key "April 2017" in post's post-info.json file.

I did try your multi dimentional array, though that is not sorting by date, only by the folder names. But anyway it is working now with the  original script just changing the above, so now to get the pager sorted. And that multi dimentional array is quite a bit longer whilst excluding where I want to filter the array as described for the script being used by the category/month menu pages. I use this script in 3 differing include files, so keeping it that much shorter does visually help.

Edited by jwbjnwolf

1 hour ago, jwbjnwolf said:

Spent a while actually getting a better understanding of what you originally sent. So ['folder'] and ['dir'] is the same thing pretty much

Essentially yes, I had no idea what was in your array to begin with so 'folder' could have been anything; $dir['dir'] is a key. What I was try to show is that it looks like you're not using key => value pairs in a logical way, you'd else need to use $dir[0] for example as it's not been named. Knowing the key => value makes life a lot easier, here's an example;

<?php
$basic_multi = array(
array('name' => "Item One", 'url' => "/item-one", 'options' => array("juice","bread","fish"), 'date' => "April 2017"),
array('name' => "Item Two", 'url' => "/item-two", 'options' => array("apple","milk","toast"), 'date' => "June 2017"),
array('name' => "Item Three", 'url' => "/item-three", 'options' => array("butter","beer","cat"), 'date' => "September 2017")
);
print_r ($basic_multi);
// or a loop
foreach($basic_multi as $b) { ?>
<ul>
<li>Name: <?php echo $b['name']; ?></li>
<li>URL: <?php echo $b['url']; ?></li>
<li>Options:<ul>
  <?php foreach($b['options'] as $o) { ?>
    <li><?php echo $o; ?></li> 
  <?php } ?>
</ul></li>
</ul>
<?php }
// or reorder
// now we sort the new array
foreach($basic_multi as $key => $row) {
  $sname[$key]  = $row['name'];
}
array_multisort($sname, SORT_ASC, $basic_multi);
foreach($basic_multi as $b) { ?>
<ul>
<li>Name: <?php echo $b['name']; ?></li>
<li>URL: <?php echo $b['url']; ?></li>
<li>Options:<ul>
  <?php foreach($b['options'] as $o) { ?>
    <li><?php echo $o; ?></li> 
  <?php } ?>
</ul></li>
</ul>
<?php } ?>

... this should explain why named keys are cool, sql with php even has mysqli_fetch_assoc to keep those keys intact, much easier to see whats going on. Run that php on http://phpfiddle.org/ and you'll see we now have keys;

Array ( [0] => Array ( [name] => Item One [url] => /item-one [options] => Array ( [0] => juice [1] => bread [2] => fish ) [date] => April 2017 ) [1] => Array ( [name] => Item Two [url] => /item-two [options] => Array ( [0] => apple [1] => milk [2] => toast ) [date] => June 2017 ) [2] => Array ( [name] => Item Three [url] => /item-three [options] => Array ( [0] => butter [1] => beer [2] => cat ) [date] => September 2017 ) )

The sort by title was just an example of sorting by one column and then by a second, SORT_ASC and SORT_DESC both work here. What I was trying to do was help to build a single array with keys and everything you need to output before the main html list.

With regards to pagination, the $pagination_url variable is to be the page on which the listings and pagination need to be. If I was to paginate this thread it would be;

$pagination_url = "/topic/87637-adding-features-to-a-dynamic-pagination-script/";

... then with the pagination php it would form the following if on page 3 and there are 4 pages;

<a href="/topic/87637-adding-features-to-a-dynamic-pagination-script/?page=2" rel="prev">Prev</a>
<a href="/topic/87637-adding-features-to-a-dynamic-pagination-script/">1</a>
<a href="/topic/87637-adding-features-to-a-dynamic-pagination-script/?page=2">2</a>
<span>3</span>
<a href="/topic/87637-adding-features-to-a-dynamic-pagination-script/?page=4">4</a>
<a href="/topic/87637-adding-features-to-a-dynamic-pagination-script/?page=4" rel="next">Next</a>

so when clicked it goes to the right url and page, sounds like making it blank isn't a go, use the real uri instead to keep it clean, something you could set at the start of the page.

Edited by BrowserBugs

  • Author

I think it may be that the script doesn't like "?=" being right after "/" in thr url or something as I also tried with having "{$_SERVER['REQUEST_URI']}" in but that did the same thing. So I've just simply put "index" and now that works as it should. 

Now to play about with styling the pager for my liking.

Though any possibility of adding first/last buttons which show accordingly like the prev/next buttons do?

Edited by jwbjnwolf

  • Author

Brilliant. Played about with css as well as changing the active page from <span> to <a class="active">, and have it looking quite nicely!

232800260_Screenshot_Internet_20180709-2230472.png.74e0c8f44527d4fa6e95edc48f75ae88.png

Though, one thing I notice is previous keeps going back to page 1 regardless of current page. That's the only thing that's now been done incorrectly. Is that because I've changed <span> to <a class="active">?

Edit: Just changed the last text to last page number and removed the first, as really knowing the total pages is all that's needed really, and allows me to have two number buttons each side of the active page without it going off onto a second row on mobile, whilst keeping it at a reasonable size.

Edited by jwbjnwolf

Ah, sorry spotted the bug, stray "'";

if($page > 1){ $prevpage = $page - 1; echo "<a href='" . $pagination_url . "'"; if($prevpage>= 2) { echo "?page=".$prevpage; }; echo "' rel='prev'>Prev</a>"; }

should be

if($page > 1){ $prevpage = $page - 1; echo "<a href='" . $pagination_url; if($prevpage>= 2) { echo "?page=".$prevpage; }; echo "' rel='prev'>Prev</a>"; }

 

  • Author

Brilliant thanks! Something I worked out yesterday whilst I was waiting for you to get back on that, how to print the categories from the json into the html as links to the categories of the same names. As well as also finding how to use htaccess for changing uppercase to lowercase.

112909517_Screenshot_Internet_20180710-1026182.png.29064054320e60c82d3ce5e165216f3d.png

Very impressed with all this now.

Lastly, how do I can I add this pager in another place as well such as above the folder array at the top of the page so that people can use it without scrolling down?

10 minutes ago, jwbjnwolf said:

Brilliant thanks! Something I worked out yesterday whilst I was waiting for you to get back on that, how to print the categories from the json into the html as links to the categories of the same names. As well as also finding how to use htaccess for changing uppercase to lowercase.

Yep arrays in arrays = multidimensional array. In my $basic_multi example it uses the array $b['options'] for the second list. The reason keys are important is because it makes life easier if things move around, plus you can find single things easily;

<?php
$basic_multi = array(
array('name' => "Item One", 'url' => "/item-one", 'options' => array("juice","bread","fish"), 'date' => "April 2017"),
array('name' => "Item Two", 'url' => "/item-two", 'options' => array("apple","milk","toast"), 'date' => "June 2017"),
array('name' => "Item Three", 'url' => "/item-three", 'options' => array("butter","beer","cat"), 'date' => "September 2017")
);
echo $basic_multi[1]['options'][2]; // Is Toast
foreach($basic_multi as $b){
echo $b['options'][2]; // Is also toast
}
?>

 With regards to htaccess it can be [nc] which doesn't make a difference on case, probably my go to for sites. PHP has enough toys for sorting out case;

<?php
$word = "UPPERCASE WORDS";
echo strtolower($word); // "uppercase words"
echo ucfirst(strtolower($word)); // "Uppercase words"
echo ucwords(strtolower($word)); // "Uppercase Words"
?>

 

51 minutes ago, jwbjnwolf said:

Lastly, how do I can I add this pager in another place as well such as above the folder array at the top of the page so that people can use it without scrolling down?

Just copy the pagination and move it above, but the array sorting etc needs to be before both. I normally do all my array sorting etc above the opining <html> so it's complete and ready to roll before the page gets displayed. This means you can handle any problems before the page sends a header, so for example 301 if the page number is higher than the total pages.

<?php // Do all your array work here as $page will be set, $dirinfo_arr will be ready etc. ?>
<html>
<head>
<title>Title</title>
</head>
<body>
  <h1>Title</h1>
  <?php // output the pagination $page ?>
  <div>1 | 2 | 3</div>
  <?php // output $dirinfo_arr ?>
  <div>Item One</div>
  <?php // output the pagination again $page ?>
  <div>1 | 2 | 3</div>
</body>
</html>

 

  • Author

Ok thanks! Worked it out that needs to be just before the foreach array slice line. 

Got the pagination and pager scripts in their own files including in the array script, so keeps the array script files very neat as well as obviously don't need to duplicate the pagingation/pager scripts for other array scripts for other parts of my site etc.

Thanks for all the help :)

  • 1 month later...
11 minutes ago, rallport said:

If I'm on page 1 or page 10, the correct query is ran. You can control the pagination template via editing a small view partial.

I'm lost as to why people would go ahead and write their own low level code like this nowadays.

The reason is that many frameworks never question, they simply "do". If you're on page one or page ten it'll work, if you're on page 3567 it will work, but should it? Are there enough results that page 3567 will actually have results, and if not what headers would the page give? Here's an example, lets look at shopify, here's a store built with shopify, see https://shop.goodasgoldshop.com/collections/mens?page=3567 ... uh, is that 200 ok? Ah hang on, maybe there's a canonical, uh yes, it's the empty page, same as the og so what happens when I share?

Now when we check their xml sitemap they should have around 1476 pages to index, but with a site check on Google it thinks there's "About 3,090 results"; where did the extra 1614 pages come from?

Developers need to fathom some degree of optimisation, I do a lot of technical clean up for clients in this very position after these sorts of developer mistakes, just my two-pence worth as always.

50 minutes ago, rallport said:

The Url you've posted is very bad for a number of reasons. A 200 HTTP status is returned, a canonical is set to the current url, no 404 status is set or meta noindex set.

However, you are using hosted ecommerce software, so you'rte at the mercy of Shopify.

Hahaha yeah mate, it's not my site and I don't know the owner,  was simply finding an easy example where a developer had relied on a framework (Shopify uses Craft) and never stopped to think. Too often these days people are simply using plug and play without a thought that the very framework they rely upon might not be correct.

Just as @rbrtsmith says about javascript, a solid foundation in vanilla goes a long way, for me it's the same with php. I learnt the longhand way to ensure I know the core language and principals, frameworks are handy for speed but IMO only if you fathom what is actually happening behind the scenes. I'm worried our industry will end up with a 'click to install' mentality, if the old skool vanilla writers die out the internet is doomed ;) 

  • Author
1 hour ago, BrowserBugs said:

frameworks are handy for speed but IMO only if you fathom what is actually happening behind the scenes.

When I first started out with my site, the amount that said I was stupid for not simply using bootstrap etc for my site rather than doing things myself. This is the very thing I did such that, do it all myself to build my knowledge of the coding rather than relying on what id and classes achieve what, which may probably not do so without or with a different framework etc.

If I didn't do my site just mainly for my personal self, I would definitely look into frameworks and possibly CMS software too.

But for myself personally with my site, I still am not fond of using frameworks and staying away from CMS is something I much prefer.

If I was busy adding to my site day in, day out, probably I would, but the aspect of learning how to do things without any frameworks/CMS, to get to know the languages more, that's the main reason I enjoy web design/coding.

I'm not familiar with PHP frameworks, so I wasn't aware of such what you've said about rallport. When it comes to PHP, I'm mainly just familiar with creating scripts which mostly are indiviual that I then use and integrate using includes etc.

Still though, when it comes to frameworks, I'd prefer to have gone the hard way, and be able to work out easier how I could possibly fix an error, rather than there turns out to be some error in a framework that I can't myself fix, so am stuck until the devs fix that. Maybe it's not something that likely to happen with a "stable" released framework, but at least until I have a bigger understanding and if I start doing web coding for anything other than personal use, I've got basically everything I want code wise on my site. As long as things continue to function well, I'm not fussed in getting my head around getting to know frameworks which from what I've seen do things in a lot of different ways to how I've done stuff for how I want them.

Edited by jwbjnwolf
didn't mean to tag rbrtsmith whoops

Totally understand mate. I'm not a framework hater, I find them fascinating, as you describe...

18 minutes ago, jwbjnwolf said:

When it comes to PHP, I'm mainly just familiar with creating scripts which mostly are indiviual that I then use and integrate using includes etc.

... this is technically your library / framework, it's just custom to you. The benefit of everyone on a team using one framework is ease of code management, that said there will be times when what you need to achieve can step way outside the scope of a framework, at times like these it'll probably need to be done the old fashioned way, pure PHP. The example from rallport is the Laravel way, shorthand to access something someone else wrote and included in the framework to save writing one from scratch, Craft Paginate will do the same thing, just a different way. The outcome is no different than using your own pagination function. 

Maybe I'm just a grumpy old man stuck in his ways, I have been working with PHP since version 4.1 which was released in 2001. In context for example the Laravel framework was initially released in 2011 but it's still built with PHP. Some roles want you to know WordPress, some Craft, Laravel, Magento ... all have their benefits, limitations and preferences but they all share the same core language PHP.

It's really down to what you want to learn, I've discovered so much working with native php that I doubt I would have discovered using a framework.

24 minutes ago, BrowserBugs said:

Totally understand mate. I'm not a framework hater, I find them fascinating, as you describe...

... this is technically your library / framework, it's just custom to you. The benefit of everyone on a team using one framework is ease of code management, that said there will be times when what you need to achieve can step way outside the scope of a framework, at times like these it'll probably need to be done the old fashioned way, pure PHP. The example from rallport is the Laravel way, shorthand to access something someone else wrote and included in the framework to save writing one from scratch, Craft Paginate will do the same thing, just a different way. The outcome is no different than using your own pagination function. 

Maybe I'm just a grumpy old man stuck in his ways, I have been working with PHP since version 4.1 which was released in 2001. In context for example the Laravel framework was initially released in 2011 but it's still built with PHP. Some roles want you to know WordPress, some Craft, Laravel, Magento ... all have their benefits, limitations and preferences but they all share the same core language PHP.

It's really down to what you want to learn, I've discovered so much working with native php that I doubt I would have discovered using a framework.

Frameworks like Laravel still allow you to roll your own, by abstracting a lot away they can take a lot of burden away from the developer making it easy to upgrade and develop on. CMS's have limitations because they have a pre-built system around content, most frameworks are empty, and you build what you want using the framework conventions and architecture. This guarantees consistency between the things you build, and allows other developers using the framework to not have to think too hard about where code is stored, and how it connects together.

I haven't really seen anything in Laravel that can't be done, I'd be surprised if someone is using a script on here that can't be built using a framework, as you're still essentially writing PHP. It also tackles many parts that developers who try and roll their own often fail badly at, like secure authentication. The amount of login scripts, even on here, that are where near secure enough is astounding.

Ok will look into laravel, see if my old grey matter can grasp it, just find it so much easier to write raw, 16 years and counting without a framework.

I find my biggest hangup is peeps who install say WordPress and tweak a bit of a template consider themselves a "developer", must be the same gripe for those who can design seeing people reuse a theme and say they are a "designer", painting by numbers doesn't make an artist ;) 

11 hours ago, rallport said:

Purely out of interest (and me being nosy), do you work as part of a team or freelance?

I'm a bit of everything, simplest is i'm freelance / contractor but these days I lean towards technical optimisation, this is normally a contract at a larger business or agency but when I'm there they have developers, front end and content teams in place so i'm more investigation of problems around indexing, architecture and speed which are discussed with the relevant team as how best to approach them. I am normally impressed by their dev teams and their experience, regardless of framework or language I find if I show them a concept in native php they grasp it and then use their weapon of choice to execute it in their own way, regardless how they went about it the outcome is the same and so all is well.

When I freelance or work on my own projects I fly solo, developer, optimisation, design, content manager, tea boy ... these projects are normally small to medium size businesses who want to rank but have no in-house teams to rely on and normally some poor Wix / Yell excuse for a website to start with. As a team of one I have no need to collaborate with others, probably why I considered learning a framework vs expanding my knowledge in the vanilla languages seemed a bit of a waste of time. Writing from scratch I don't start with a blank page, I have a bank of php functions I've written for different purposes which I pull in for depending on requirement such as image upload and compress functions. These units in my mind are easy to manage and update, simply include the new function and the values will match up.

I will say tho what I have learnt this way forms a lot of my technical optimisation concepts, I've seen first hand through my own work what happens when things go south, just like the example of phantom pages thanks to pagination problems.

On 8/17/2018 at 10:02 AM, BrowserBugs said:

Ok will look into laravel, see if my old grey matter can grasp it, just find it so much easier to write raw, 16 years and counting without a framework.

I find my biggest hangup is peeps who install say WordPress and tweak a bit of a template consider themselves a "developer", must be the same gripe for those who can design seeing people reuse a theme and say they are a "designer", painting by numbers doesn't make an artist ;) 

After 16 years you are still building everything from scratch?  Once i moved to Codeigniter I never looked back. It provides you with essential libraries such as the database Query builder. Instead of doing this... 

<?php
$query = mysqli_query($conn,"SELECT * FROM `posts` ORDER BY `id` LIMIT 20");
 
if($query->num_rows() > 0){
	while($row = mysqli_fetch_object($query)):
  	echo $row->title."<br />";
  	endwhile;
}

you can do this using the frameworks query builder inside a model...

<?php
class My_model extends CI_Model
{
  //Get posts
  public function get_posts()
  {
   		$query = $this->db->order_by('id','DESC')
          		->limit(20)
          		->get('posts'); 
    
    	return $query->result();
  }
}

And then pass the data to the view within the controller. 

Unless someone is just learning PHP or the project is simply way to small to warrant a framework then idk what reason anyone would choose to write stuff from scratch. You can always add functionality to the framework by building your own libraries,helpers etc... without ever having to touch the core code.

Edited by webdeveloper93

Looking at the examples I can't see a reason why the second is better? Both return an array of 20 results? Database queries are simple enough, and if the query is needed in multiple templates then a function in the core would do the same?

2 hours ago, BrowserBugs said:

Looking at the examples I can't see a reason why the second is better? Both return an array of 20 results? Database queries are simple enough, and if the query is needed in multiple templates then a function in the core would do the same?

Well one benefit of a query builder such as codeigniters is that it will escape the data for you using mysqli_escape_string and helps tremendously when building more complex queries . Not to mention the many other classes a good framework consists of such as ...

  • Form validation
  • Pagination
  • Upload
  • Security 
  • Etc...

Also helpers such as 

  • HTML helper
  • Form helper
  • Date helper
  • Array helper
  • etc...

And like i said if for any reason you need a different library or helper you can build your own.

I guess i just don't see the purpose in building these classes from scratch. Maybe just try one framework out if you ever get the time.

Edited by webdeveloper93

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.