Is this facebook link populated fully from the DB? Or, is it a physical file with PHP in it? Just, how is this page called?
http://www.facebook.com/profile.php?id=49300915&sk=photos
They probably do something like:
if(isset($_GET['id'], $_GET['sk'])) {
mysql_query("SELECT info, photos FROM users WHERE id = '$id'");
}
I'm trying to ask, how do they include this page? Is it like Drupal / any CMS where the PHP and page is stored in the DB, or is it a physical file on the server? If the latter, what's the best way to get the file (case insensitive URL)?
I would have a class with a single method, which reads 'sk' and runs another method, depending on what it's value is.
One method would be 'photos' which would read 'id' and fetch a photo from the database. It would then run another method, displayPage, which will display a page from that data.
The displayPage method takes a "template" filename and an array of variables to provide to the template. It sets up a smarty object, provides the variables, and instructs it to display the template.
Inside the template, I'd include another template for the global header that's on every page in the site, then i'd have the html page content, using smarty to insert dynamic values, then include a global footer.
Note that i've simplified this system a lot. A real page like that would take me a week to write all the code, since a big website does a lot of stuff just to display a simple page (for example: find out if the logged in user actually has access to the page... i don't have access to the example one you gave).
<?php
// profile.php
class ProfileController
{
public function run()
{
if ($_GET['sk'] == 'photos')
return $this->photosPage();
}
protected function photosPage()
{
$id = (int)$_GET['id'];
$result = mysql_query("select * from photo where id = $id");
$photo = mysql_fetch_object($photo);
$this->displayPage('view-photo.tpl', array('photo' => $photo);
}
protected function displayPage($templateFile, $templateVariables)
{
$smarty = new Smarty();
foreach ($templateVariables as $variableName => $variableValue) {
$smarty->assign($variableName, $variableValue);
}
$smarty->display($templateFile);
}
}
$conntroller = new ProfileController();
$controller->run();
And the smarty code:
<!-- view-photo.tpl -->
{include file='head.tpl'}
<h1>View Photo {$photo->name|escape}</h1>
<img src="{$photo->src|escape}" width="{$photo->width|escape} height="{$photo->height|escape}>
{include file='foot.tpl'}
Related
I have a project in which is develop in codeigniter.
The project is like this:
-root
--controller
---Slider.php
--models
---My_data.php
--views
---slider_view.php
---giris.php
Slider.php
public function manset_al(){
$title['title']='manşet listesi';
$this->load->model('My_data');
$data['manset']= $this->My_data->get_manset();
$this->load->view('slider_view' ,$data);
}
My_data.php code is;
public function get_manset() {
// $sorgu =
// mysql_query("select * from manset, haberler
// where manset.onay='1' and manset.link=haberler.id and haberler.onay='1'
// order by haberler.id desc");
$this->db->select('*');
$this->db->from('manset as man, haberler as hab');
$this->db->where('man.link=hab.id');
$this->db->where('hab.onay=1');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return $query->result();
}
slider_view.php code is:
foreach($manset as $row){
$baslik =$row->baslik;
$icerik =$row->icerik;
$link =$row->link;
$img_path =$row->img_path;
$giris =$row->giris;
$cikis =$row->cikis;
echo '
<div>
<img data-u="image" src="'.$img_path.'"/>
<div data-u="thumb"> <h5 style="color:white; margin:10px;">'.$baslik.' </h5> </div>
</div>';
}
Now when i called
http//example.com/index.php/Slider/manset_al
every think is ok - the slider is running.
But when i get the slider in giris.php with this code;
$this->load->view('slider_view');
it's not run and say: undefined variable manset;
how can ı fix it?
Thank you.
We're missing some details to quickly solve this one: namely, how is giris.php called, exactly? Without those details I can only give a general answer.
This error means that you are trying to access data in your template file that you haven't passed to the templating system. For instance, in your controller (Slider.php) you pass data off to the templates here:
$this->load->view('slider_view' ,$data);
The $data is the important part: codeigniter takes every entry in that array and creates a variable in the template system whos name corresponds to the name of each key. Therefore, foreach( $manset as $row ) works because $data has a key named manset that has each row in it. You can see that in giris.php you are specifically not sending any data to the template:
$this->load->view('slider_view');
Notice the lack of a second parameter. Of course your file structure implies that giris.php is itself a view file, which means that whatever controller method that called giris.php needs to be the one sending data out to the view. So generally, that is the answer: whatever controller is ultimately calling giris.php needs to be sending the slider information out to the templating system, but isn't. Without more details on how giris.php is actually called, that is as specific as I can get.
hi i've got a gallery page. this gallery page has a gallery image object with an has_many relation.
private static $has_many = array(
'GalleryImages' => 'GalleryObject'
);
my gallery object has an image upload field. I want to set the upload folder to the title of the gallery page
i tried this with no result
$visual->setFolderName('Galerie/'.$this->Gallery()->Title);
and this (what i would prefer)
public function getGalleryTitle() {
$galleryTitle = $this->Gallery()->Title->First();
$uploadFolder = str_replace(' ', '-', $this->$galleryTitle);
return $uploadFolder;
}
$visual->setFolderName('Galerie/'.$this->$uploadFolder);
the second returns and error (undefined variable uploadFolder ?!) and my upload folder is now set to "Galerie/DataList"
can someone tell me how to convert the output of $uploadFolder so that i get back the title?
EDIT:
GalleryHolder: http://www.sspaste.com/paste/show/5267dea3579a6
GalleryPage: http://www.sspaste.com/paste/show/5267dee4c9752
GalleryObject: http://www.sspaste.com/paste/show/5267df0af1a65
you where almost there..
Here is your edited getGalleryTitle() function.
It is basically checking if the GalleryObject has a parent Gallery via $this->GalleryID. Since it is a has_one relation the column will be named GalleryID.
Then we get the Gallery object with $this->Gallery() and get it's title with $gallery->Title.
I've also replaced your str_replace with SilverStripe's URLSegmentFilter class. Which will removed spaces and other special characters non welcome in URL, a better solution.
public function getGalleryTitle()
{
if ( $this->GalleryID )
{
$gallery = $this->Gallery();
$filter = new URLSegmentFilter();
return $filter->filter( $gallery->Title );
}
else{
return 'default';
}
}
Then in the getCMSFields() function, when creating your UploadField we just call the getGalleryTitle() function that returns the string for the folder name.
$visual = new UploadField('Visual', _t('Dict.IMAGE', 'Image'));
$visual->setFolderName('Galerie/'.$this->getGalleryTitle());
A few notes..
$this references the current Object instance, so you can't use $this->$galleryTitle to access a variable you just created in your function, $galleryTitle by itself is enough.
You were calling $this->$uploadFolder in setFolderName, this doesn't work for the same reason, and also, using $uploadFolder by itself wouldn't work since this variable was created in the scope of another function. So we just call the function we defined on our Object with $this->getGalleryTitle() since it returns the value we want.
This should work fine, but keep in mind that if the Title of the Gallery changes at some point, the folder name will change too. So you might end up with images uploaded in many different folders for the same gallery... I personally wouldn't advise it, unless you implement some kind of "Title locking system" or some way to keep the "correct" or first "valid/acceptable" Gallery title in a separate object property that can't be edited and use this in the folder name.
I usually only use the ID in those case ($gallery->ID), as this will not change.
edit
Another version of getGalleryTitle() that should work even if the GalleryObject isn't saved yet.
public function getGalleryTitle()
{
$parentID = Session::get('CMSMain')['currentPage'];
if ( $parentID )
{
$gallery = Page::get()->byID( $parentID );
$filter = new URLSegmentFilter();
return $filter->filter( $gallery->Title );
}
else{
return 'default';
}
}
First, I check to see whether we're on the CMSSettingsPage or in a ModelAdmin page (Should you be using them). You want to get all the information about which class the controller is managing as it's data record. (If you have firebug, FB($this) in getCMSFields() on the related DataObject (DO) will show you the page managed under DataRecord)
Controller::curr()->currentPage() will get you the current page the DO is being managed on, and ->URLSegment will get the page url name, though you could use Title or MenuTitle also.
Here is an example which will set up a folder underneath assets/Headers to save images in. Running this on the HomePage (ie URL Segment 'home') will create and save objects into the folder /assets/Headers/home.
if (Controller::curr()->class == 'CMSSettingsController' || Controller::curr() instanceof Modeladmin) {
$uploadField->setFolderName('Headers');
}
else
{
$uploadField->setFolderName('Headers/' . Controller::curr()->currentPage()->URLSegment);
}
This code for extract files dir and title. The user download when clicked the file link. I need to count then number of downloads. How to do this with cakephp or php?
downloads_controller.php:
function index() {
$this->set('downloads', $this->paginate());
}
downloads/index.ctp:
<?php
$title = $download['Download']['title'];
// output filetitle
$filename = '/files/'.$download['Download']['filename'];
// output http://localhost/tet/files/un5titled0.rar
echo $this->Html->link($title, $filename,array('escape' => false));
?>
not this way i am afraid.
you either need to redirect from an action (which counts before redirecting) or use Media view to pass it through.
thats how I do it.
In the action you can then raise the count prior to sending the file.
If you want to count downloads, you should create a function that serves those downloads and create a field in your database that increments downloads each time this function is called.. For example
Call the following function from your view passing the $filename and the $id
To try out at first use, taking ID=4 as one of the downloads ID in your DB
http://www.yourdomain.com/downloads/download/4
And Then your controller would be...
Class DownloadsController extends AppController{
// All your other functions here
function download($id = null){
$this->Article->updateAll(
array('Download.count' => 'Download.count+1'),
array('Download.id' => $id)
);
$download = $this->Download->findById($id);
$this->set('filename', $download['Download']['filename']);
//$filename is an array that can then be used in your view to pass the file for download. to find out what is has you can use debug($filename) in your view
}
}
Then you need to create a special layout so the browser knows that the request file is a download and you will also need to create a view for download.ctp. Basically when you click the file link on your page, it will call this function which will use its view to serve the file.
You can access the following which will provide some insight on what needs to be done..
TUTORIAL LINK
There are lots of techniques, though in the simplest way, you can use a text file to do this.
Create a txt file and write 0 (zero) into it.
In your index function, read the content of your file.
$counter = file_read_contents('counter.txt');
Increase the read value by 1.
$counter++;
Write new value into file again.
file_put_contents('counter.txt', $counter);
So, it counts downloads and keep number in that file.
function download($id = null) {
$download = $this->Download->findById($id);
$this->set(compact('download'));
if(!empty($id)) {
// increment the number of items downloads
$this->Download->save(array(
'Download' => array(
'id' => $id,
'counts' => ($download['Download']['counts'] + 1)
)
));
}
header('Location: http://localhost/tet/files/'.$download['Download']['filename']);
exit();
}
in the controller i have :
$paginator = Zend_Paginator::factory($mdlPost->getPosts($this->moduleData->accordion, 'name ASC'));
if(isset($params['cities'])) {
$paginator->setCurrentPageNumber(intval($params['cities']));
}
$paginator->setItemCountPerPage(4);
$this->view->posts = $paginator;
in the view's i have some thing like this :
if ($this->posts != null) {?>
<div id="cities_accord" class="news">
<?php echo $this->partialLoop('partials/post-min.phtml', $this->posts); ?>
</div>
<?php echo $this->paginationControl($this->posts,
'Sliding',
'public/pagination_cont.phtml');
}
the partial/post-min.phtml
<?php
$color = array(1=>'spring',2=>'summer',3=>'autumn',4=>'winter');
?>
<div id='<?php echo $color[$this->partialCounter] ?>' class="accordion_post">
<?php
$link = Digitalus_Uri::get(false, false, array('openCity' =>
$this->id));//$color[$this->partialCounter]));
?>
<h1 class="accordion_post_title"><?php echo $this->title ?></h1>
<p><?php echo $this->teaser ?> <i>read more</i></p>
</div>
the pagination_cont.phtml taken from this link zend ( http://framework.zend.com/manual/en/zend.paginator.usage.html )
will show links that will pass params to the controller to fetch the corresponding whole page which is working alright for now
but i want to change this so that i will be able ajaxify the returned ( i.e. only a single paginated value rather than reloading the whole page ) results how can i do that using jquery and what should i change ..
** EDIT: it would be nice to have a fail-save ,if possible, for browsers(users) that disabled javascript to see the same thing by reloading the page (i.e. keeping the current status for if(javascript_not_enabled ))**
This is what I've done in the past.
First, setup the AjaxContext action helper to enable the html context on your controller action.
Add a .ajax.phtml view that just contains the section of markup that may be replaced via AJAX as well as the pagination control links. You can probably just copy this out of your normal view. Replace that section in your normal view with something like
<div id="reloadable-content">
<?php echo $this->render('controller/action.ajax.phtml') ?>
</div>
This will ensure that your initial and any non-AJAX requests will still include the right content. The <div> id is purely for referencing the loadable block in JavaScript.
Also make sure you include your JS file (using headScript) in the normal view only.
Now, in your JS file, unobtrusively add the appropriate event binding to the paginator links. As you'll be replacing the pagination control section in order to reflect the correct current page and other links, it's probably best to do this using the jQuery live binding. I'm also assuming you'll wrap the pagination control with some kind of identifiable element (<div class="pagination-control"> for example)
$('.pagination-control').find('a').live('click', function(e) {
var link = $(this);
$('#reloadable-content').load(link.attr('href'), { format: 'html' });
return false;
});
Keep in mind that in using this method, you will lose the ability to navigate the paged requests using the normal back / forward browser buttons. You will also lose the ability to bookmark pages directly (though you could always provide a permanent link to the current page as part of the AJAX loaded content).
You can use something like the jQuery history plugin if you're really concerned but that will require more client-side work.
Another caveat is that the above will only work with pagination links. If you want to use a form with dropdown page selection, you need to add another event handler for the submission.
GOT IT and big Thanks to #Phil Brown :
in the controller int() change the response type to json
class NewsController extends Zend_Controller_Action
{
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('list', 'JSON')
->initContext();
}
// ...
}
public listAtcion() {
// .............
$paginator = Zend_Paginator::factory($mdlPost->getPosts($this->moduleData->accordion, 'name ASC'));
if(isset($params['cities'])) {
$paginator->setCurrentPageNumber(intval($params['cities']));
}
$paginator->setItemCountPerPage(4);
$post = array();
foreach($paginator as $post ) {
$post[] = $post;
}
$this->view->post = $paginator;
#TODO //add a check here for non-ajax requests (#improvment)
$this->view->posts = $paginator;
}
in one of the views (most probably in the pagination_cont.phtml) on the pagination controller add the ajax links
<?= $this->ajaxLink (
$this->url('cities'=>$this->page_num),array('id'=>'div_id','complete'=>'js_method(json_data)','method'=>post) ,array('format'=>'JSON'));
and add a JavaScript function of js_method(json_data) to modify the div with id = 'div_id' with a json data
function js_method(json_data) {
var content = parse.JSON(json_data);
$('#div_id').html('');
//fill it with the reposnse content some thing like $('#div_id').append(content);
}
I dont understand what the layout is, in the view. I asked a question previously on the subject of templating in PHP, but I still dont quite understand. I assume that you create a general layout for the site and then include each specific view within that layout.... I would like to know how to go about doing this. Also, are should the templates be made using just html, because I also looked at these things called helpers.... I'm just confused on the View part of the MVC, and the actual templates and how they're made. I learn best with examples, If you guys have any.
Also, a more important question, lets say I had a form that a user saw only if he was logged in, would I control that in the view, or in the controller?
So Would i do
in the controller
include 'header';
if(isset($_SESSION['userID'])){
include 'form';
}
include 'footer';
or
in the template
<html>
<?php if(isset($_SESSION['user_id'])): ?>
<form>....</form>
<?php endif;?>
</html>
EDIT
So, is there an include statement from within the layout to see the specific view template? how so?
a layout is whatever you have around your main content area. Usually on a normal website it would be any sidebar,header,footer. Most of MVC framework provide the layout to avoid to repeat those parts in all views.
You can imagine if like you have two view cascaded
you actual view is rendered, this content is saved
the layout view (all the items around the content) are rendered and your content is included in that output
for your login question actually your would have to do both
on the controller and the view
$this->view->isLogged = isset($_SESSION['userID']);
in the view
<?php if($isLogged): ?>
<form>....</form>
<?php endif;?>
I hesitate to answer this question only because of the religious fervor that surrounds it.
To get a really good understanding of the issues behind the general concepts see This Wiki Discussion Page This is the discussion page around the wiki MVC article.
Here is the rule of thumb I like to follow (BTW I use CodeIgniter and it kind of sounds like you are too):
The "view" should have virtually no logic. It should only be HTML (in the web world) with peppered PHP that simply echos variables. In your example you would break out the form into its own view and the controller would determine if was loaded or not.
I like to look at it this way: The view should have no concept of where the data comes from or where it is going. The model should be view agnostic. The controller meshes data from the model and provides it to the view - and it takes input from the view and filters it to the model.
Here is a quick and dirty (untested - but it should get the point across) example:
Theapp.php (The App controller)
class Theapp extends Controller
{
var $_authenticated;
var $_user;
var $_menu; // array of menus
function __construct()
{
session_start();
if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'])
{
$this->_authenticated = $_SESSION['authenticated']; // or some such thing
$this->_user = $_SESSION['user'];
}
$this->_menu = array("Logout", "Help", "More");
parent::__construct();
$this->loadView("welcome"); // loads primary welcome view - but not necessarily a complete "html" page
}
function index()
{
if (!$this->_authenticated)
$this->loadView("loginform");
else
{
$viewData['menu'] = $this->_menu;
$viewData['user'] = $this->_user;
$this->loadView("menu", $viewData);
}
}
function login()
{
/* code to authenticate user */
}
function Logout() { /* code to process Logout menu selection */ }
function Help() { /* code to process Help menu selection */ }
function More() { /* code to process More menu selection */ }
}
welcome.php
<h1> Welcome to this quick and dirty app!</h1>
All sorts of good HTML, javascript, etc would be put in here!
loginform.php
<form action"/Theapp/login" method="post">
User: <input id='user' name='user'>
Pass: <input id='pass' name='pass' type='password'>
<input type='submit'>
</form>
menu.php
Hi <?= $user ?>!<br>
Here's your menu<br>
<? foreach ($menu as $option) { ?>
<div class='menuOption'><a href='/Theapp/<?=$option?>'><?=$option?></a></div>
<? } ?>
Hope this helps.
If your not using a framework, then a simple way to have a layout and a view can be like so:
<?php
function layout($layout_params) {
extract($layout_params);
# Remember: $layout_content must be echoed for the view to be seen.
ob_start();
include "layout_page.php";
$html = ob_get_contents();
ob_end_clean();
return $html;
}
function view($view_params) {
extract($view_params);
ob_start();
include "home_page.php";
$html = ob_get_contents();
ob_end_clean();
return $html;
}
#
# The variable $parameters is extracted and $params becomes a variable in the view as an array,
# $logged_in is also now avaiable in the view
#
$parameters = array("params" => array("name" => "joe"), "logged_in" => false);
$view_content = view($parameters); # => Returns the HTML content for home_page.php
# Now we need the layout content to include the view:
# The layout file will expect a variable called $layout_content to be the html view.
# So we need to set $layout_content to be $view_content
$parameters["layout_content"] = $view_content;
# We no longer need $view_content so we can unset the variable
unset($view_content);
# When $paramters is extracted it will have $layout_content as a variable:
$layout_content = layout_view($paramters); # => Returns the HTML content for the layout_page.php
# Now send the results to the browser
echo $layout_content;
?>