Storing PHP in a database - php

If I had a menubar that was totally dynamic where you can add pages to it and remove pages from it (being stored in database) . These pages all have content in a database , things like an article however I cant store PHP code in the database so I cant add things like dynamic tables within the page, is there any way around this or am I missing something. I am using Laravel. Feel free to ask to elaborate as I dont think this is as concise as it could be.

First of all: Saving php code into a database, or doing anything requireing eval is usually wrong code.
What you could do is make classes which renders the right dynamic view, Make an array of anonymous functions which can instantiate the classes, and put the array keys into the database.
your code would look like this:
class yourrenderClassLol{
function render(){echo"lol";}
}
$classes["yourrenderClass"]=function(){
static $instance=NULL;
if($instance==NULL){
$instance=new yourrenderClassLol();
}
return $instance
}
$classes["yourrenderClass"]()->render();

Related

Static classes and global variables

I'm using FuelPHP 1.6.1 with a lot of static classes, this seems to work out quite nice. Now I have a Menu generator that loads some data
$menu = Menu::generate();
It loads some data and stores this in static::$data
How would I go for another class to load just that? I'm getting null results, probably because I'm doing something wrong, but I dont see what I'm doing wrong at the moment.
Also, yes, the Menu::$data is declared public static $data
Any tips?
Using FuelPHP's Session::set() does the job, but only after a reload, I need the data straight away in other classes, and loading it again results into double queries (which I dont want)
PHP's $_SESSION is not used, nor will be used.
Turns out, in my way of showing views and menu, menu::generate() came after the other classes that needed it, put it at the start and using FuelPHP's Session::set() did the job

Codeigniter 2 using a library in a loop

I have an issue I keep hitting the wall on and I need some suggestions on the best way around this.
I got a loop that grabs data from my model, but within that loop, I have to validate it against a library, but I cant seem to find a good way to do that.
for example, I got a model method that looks similar to this:
public function GetUserList() {
$this->db->select('username, email, joindate, rank')->from('user');
$query = $this->db->get();
//loop through data and bind to an array.
foreach ($query->result() as $row) {
$users[] = $row;
}
return $users;
}
when the page loads the user will see a list of users and their info, but some users don't want their email address to be shown, we then have to use the user library to fetch the settings for that user and see if we should hide that email or not.
the only solution i found was to use a helper function as a detour, but I feel that is going to bite me in the future duplicating things like that.
the other issue I found was once you created the library it didn't restart the object as a new one (like it would in vanilla PHP).
I'm hoping someone has a good way to resolve a setback like this.
One last item, if it makes a difference, I'm also using Twig to handle my views.
You do not need to load every library file using the load() function. The load() function is for loading a single instance in the global (CI) namespace. If you want to work with a collection of objects, you should require the file like you normally would in PHP.
I would personally join on your preferences table if possible. That way you wouldn't have to do a separate query for every single user.

Beginner CodeIgniter concepts - Reusable view code, where to go? (Helper?)

I am a beginner with CodeIgniter still struggling to get a complete grasp on how to use the MVC ideology most cleanly.
I am writing a basic CMS system with the ability to vote on entries and follow people etc, consequently, I have found myself using the same or similar pieces of code across multiple views here and there consisting of various pieces of html and logic such as:
Voting panel
Follow/Unfollow panel
Login/Logout panel
Code to check if a user is logged in etc...
I am wondering where to put this code so it can be unified? I am thinking a helper is the way to go? If I declare the helper in the controller, it can be called from the corresponding view right?
Some of the elements are dynamic - such as a follow/unfollow button - It would need to check if you are already following the user or not and display the appropriate button, which would require a model to check. What I have now is that all the logic is in the controller and it returns an appropriate button, but it seems weird to be returning formed html code in a controller return as well. Should it be more like:
controller checks if you are following someone
the controller passes a boolean to the view
the view calls the helper with this value to draw the appropriate button
Also, as a secondary question, I have been doing a fair bit of looping through mysql arrays in foreach loops to process mysql results returned from the view. It seems like my views are getting somewhat complicated, but I can't think of another way to do it, although perhaps this should be done in another helper as well?
Apologies if this is a naive or repetitive question, there is indeed a lot of discussion surrounding this subject but it is not always easily relatable to another project.
Helpers are certainly one way to modularize anything that isn't DRY. Another is to use Partial Views. CodeIgniter looks like it supports partial views. Here's a good breakdown - not PHP specific but the discussion should be agnostic.
As far as handling user logins is concerned, you will probably want to use a static class and the singleton design pattern, which will allow you to check to see if a particular user is logged in or not anywhere in your application. There is a good tutorial here
http://www.phpandstuff.com/articles/codeigniter-doctrine-scratch-day-4-user-login
Loading the helper, I don't believe loading it in your controller will automatically load it in your view. I think you have to re load the helper in your view file, or you have to autoload the helper. (cant remember off top of head but Im pretty sure).
Regarding looping through the mysql results, you should be using a model for this, always. Any functions which are grabbing or sorting information from your applicaiton, should be done within the model. Then, in your view file you loop through the results and format the data how you choose to.
When developing http://newspapair.com which has the vote functionality you mentioned I used helpers and custom classes to spread the functionality across multiple views.
Helper - has functions without a class. So a standalone function or group of functions can be placed in a file and saved as a helper.
For instance I used a helper with generic form processing functions for NewsPapair, instead of a static class. But this is not the "best practices" thing to do. I did it this way because I already had the functions from a previous project.
As far a looping through MySQL results, try to write a query that allows the DB Server to do the heavy lifting. This will make your code more efficient. Perhaps ask a question about a specific query with example code. Plus do all of the data gathering in your Model.

When to use model or helper

I am playing around Codeignter and was curious about the structure of the application:
I am not sure when to use the model ( apparently it isnt a hard requirement)
I have a part of the header that is dynamic, so I run conditional statements ( if () {..} else {..} ) for the sake of code cleanness and clarity. Should I turn that part into a helper and refer to it instead? Or does that sound like too much of a stretch?
The models are best used for data gathering and formatting methods. Such as polling the database for blog posts and then creating post objects of them and returning them.
Then the controller uses them to fill views with the data desired, such as a title, a date, an author, and a shortened body summary.
As far as the header part, consider creating smaller views to encapsulate complex code, like a menu highlighter switch or ifs, away from more clear-cut code. Consider over-building those views. Nothing wrong with creating a view just for one tab on a menu, then calling it 10 times with different data for each of the menu items in another view.
While it seems silly for a menu, it becomes indispensable for uses like boxes to wrap widgets in, or built-in validation on a textarea view.
I am not sure when to use the model ( apparently it isnt a hard requirement)
Models are part of the MVC structure. I'd recommend you to read about it.
I have part of the header that are dynamic, I run conditional statements ( if () {..} else {..} ) for the sake of code cleanness and clarity should I turn that part into a helper? and refer to it instead? Or does that sound like too much of a stretch?
This article explains you how to use: Helpers in CodeIgniter.
You should use a model if you're reading/writing data to a database (or another data source).
You should use a helper to help you with reusable tasks. For example, you may have an authentication helper, or a form helper, etc.
I would have thought you'd be able to extend a helper to return a random header image URL you can use in an img tag, although it's been a while since I've working with CodeIgniter.

Help comprehending how the following framework fits together:

I am just getting into OOP and framework design. I have started by using the following three tutorials;
http://net.tutsplus.com/tutorials/php/creating-a-php5-framework-part-1/
http://net.tutsplus.com/tutorials/php/create-a-php5-framework-part-2/
http://net.tutsplus.com/tutorials/php/create-a-php5-framework-part-3/
This is the first framework I have tried to work with and because the tutorial is not aimed at complete novices I am finding myself having to reverse-engineer the code to see how everything works. The problem is I'm stuck.
First, I understand the basic concepts of the framework including the directory structure.
Second, I understand what the registry and database class are for (although I don't fully understand every function within them just yet).
My problem comes with the index.php, template.class.php and page.class.php files. I broadly know what each should do (although further explanation would be nice!) but I do not get how they fit together i.e. how does the index page interact with the template and page objects to actually produce the page that is displayed. I especially cannot work out in what order everything is called.
The index appears to me as:
require registry class
create instance of registry (don't quite get this bit - easier way to access database?)
store the database and template objects
creates new connection from the stored database object
choose the skin for the page
Then, and here is where I get lost:
build actual page via buildFromTemplates function (which I can't get my head round)
cache a database query
assign tab (i'm completely lost as to what a tag is!)
set page title
display content
Can anyone help break this down for me? I tried Zend before this but it was far too complicated, this one is more accessible but as you can still has me stumped (although I have started to understand objects FAR more by trying).
Thanks in advance.
Firstly I think they over complicated the implementation of the Registry pattern. I always used the following approach which is more straightforward (I'll print a simplified version of it).
class Registry {
protected static $_instances = array();
public static function add($instance, $name) {
self::$_instances[$name] = $instance;
}
public static function get($name) {
return self::$_instances[$name];
}
}
The Registry combined with the Singleton is just a mess.
Regarding the aspects where you got lost:
1. buildFromTemplates
Method accepts unlimited numbers of parameters func_get_args() as template file locations, either relative or absolute. If relative (as in skins/ not being part of the parameter send) overwrite the variable holding the name $bit with the absolute location. If the file exists read in the variable $content. Repeat until all method arguments are used and add the end result to the Page class.
2. Query cache
If the given query does not return a resource_id (which a database query should) it means the query didn't execute successfully and the method triggers and error. Otherwise save the resource_id in the property queryCache for later use. For example:
// assume $db is a reference to the database object and that this is the first
// query
$db->cacheQuery('SELECT * FROM whatever');
$results = $db->resultFromCache(0); // previous query resource_id
.... ahhh, forget it.
This is so messed up, rather recommend you start with some sane framework good for learning internal works. Like CodeIgniter, and move onwards when those concepts are clear.
This tutorial is full of wrong decisions, like errors instead of exceptions, tight coupling, custom template engine (where plain PHP would have sufficed) and more.
Even symfony, which is a big framework is not that hard to follow along the lines.
Ok, its taken me all of the last two nights and tonight (:-S) but I think I have an answer so I will post it to see if it helps anyone else.
I will start from the '//database connection' line
database connection is made
skin is chosen
'buildFromTemplates' function chosen from the 'template' class.
Set the parameter to the page you are trying to build. The layout of the page you wish to create should be stored under skins>templates>filename.
The constructer called when executing the template class will then initiate a new Page instance.
This buildFromTemplates function then takes the parameter aka the file name and then retrieves the content from the file. This will be stored in the $content variable.
the database query is then made and executs the cacheQuery function
the addTag function for the Page object you have instantiated is then called
the title of the page is then set
Finally,
the parseOutput function is called which runs the replaceBits, replaceTags and parseTitle functions. This replaces the respective code written with the page you are trying to create.
Finally the content is output to the page.

Categories