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
Related
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();
Hey guys was hoping you could help me out.
basically i'm working on a website created using codeigniter by someone else. The site has two instances, one for development and one for live. The site is still under construction which means files are constantly being changed and moved from the development site (after being tested) to the live site.
Now the thing is, the person who initially created the site made some database calls from a few views. And to access the database from the view, he manually connected to the database from the view, i.e using
$db=mysql_connect(...);
mysql_select_db(...);
This means that each time a view is changed, before copying the files from the dev site to the live site, we need to change the variables inside these views.
moving all queries to models, and then calling them through controllers would take too long, so was wondering if there was a way through which i could access the database variables in the database.php file and pass them as the variable for mysql_connect.
i tried $this->db->database but get the error "Undefined property: CI_Loader::$db"
thanks in advance
There is no way to access database object from view. And you should also not do
$db=mysql_connect(...);
mysql_select_db(...);
in view. Try to remove those calls from view. And call it from model.
That is what MVC in codeigniter used for. Othervise what is use of using codeigniter framework.
See also:
access model from view in codeigniter?
CodeIgniter - Calling a function from inside a view
Define constants in constant.php assign them database username , password , host name etc and use them anywhere you want
First of all don't be eager about moving database calls to views, than take a look at this answer: https://stackoverflow.com/a/5835321/1444604
If this site is under construction yet, it shall be much better fix all this programing issues now than later.
Remembering that mysql_* codes are deprecated and won´t go much longer be accepted by hosts.
A hint that you could use what sometimes we forget, are those options of replacing texts presents in som many text editors and IDE´s, normally with a shortcut ctrl + H, you can rewrite a lot of code in many files, but be careful, or this can get all worse.
Well... said that, what you´ve tried to do in the view $this->db->database() maybe can work if you use this code before load database. I think it should
work just like as when creating libraries.
$CI =& get_instance();
Give a look on, but even if it works, avoid it as much as you can:
https://www.codeigniter.com/user_guide/general/creating_libraries.html
Good Luck!
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.
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.
I'm playing around with CodeIgniter; hoping to convert some of my old, ugly PHP into a more maintainable framework. However, I've come across a rather frustrating roadblock - I can't seem to define methods in my views. Any time I try I get a completely blank page, and when I look in the debug log the processing seemed to stop after the view was loaded. Can I define methods within views? If not, why, and what workarounds would you suggest?
Note: The method has to do with formatting output strings.
Define your functions in a helper and load them from the controller. That way you can reuse the functions in other views, as well.
I'm not familiar with CodeIgnitor, but it could be including your templates multiple times. Try wrapping your function in a check:
if (!function_exists('myfunc'))
{
function myfunc() {}
}
CodeIgnitor is probably swallowing errors, so you could also try flushing buffers immediately before your function:
while(ob_end_flush()){}
error_reporting(E_ALL);
ini_set('display_errors', 1);
In reality though, you should probably make your string formatting code a bit more general. Your template is not really a good place to start adding functions. You'll begin duplicating code, and it defeats the purpose of having templates at all. I'd suggest experimenting with CodeIgnitor's Helpers and Plugins
Views are not meant to call controller actions. Reverse your logic, call that function in the controller and set it to a variable you sent to the view. Then you can have the if statement check that variable in your view template.
If that doesn't work for you, maybe a helper is what you need: http://codeigniter.com/user_guide/general/helpers.html