February 12, 2015 9:06 pm

How to Build a Marketplace with CakePHP 2 & Foundation 6/6

This is the last part of turned from knowing nothing about CakePHP to being able to make your own CakePHP applications. In this part we will cover the last thing left in our OffersController is the buy() method and after that you will get demo and download source code links using them you can easily run an ecommerce site.

How to Build a marketplace with CakePHP 2 & Foundation 6-6

The last thing left in our OffersController is the buy() method.

Here it is:

public function buy($offerId=null) {
			if ($offerId) {

				$hasOffer=$this->Offer->findById($offerId);
				if ($hasOffer) {
					$sql="INSERT INTO orders (offer_id, user_id,created) VALUES ('$offerId', '{$this->Auth->user('id')}', NOW())";

		$this->Offer->query($sql);
		$this->Session->setFlash("Your purchase has been send for processing.");
					$this->redirect(array(
						'controller'=>'offers',
						'action'=>'index'
						));
				}
	$this->Session->setFlash("There was an error with your request. Please try again later.");
					$this->redirect(array(
						'controller'=>'offers',
						'action'=>'index'
						));

			}

		}

Whenever a user buys something we save it into the database and redirect. (Notice that we should change this so users can confirm they want to buy the item. Currently, we only confirm with a JavaScript prompt box).

Of importance is to see that you can access any model and do your own queries on it.

$sql="INSERT INTO orders (offer_id, user_id,created) VALUES ('$offerId', '{$this->Auth->user('id')}', NOW())";

$this->Offer->query($sql);

You access the model’s query method and pass it the SQL you want to execute. You can save the results into a variable and process them just as if you are using built-in methods.

It can be described as: $results = $this->ModelName->query(“SQL STRING”);

We do not have a View for the buy() method as we redirect and do not render anything at this point.

OrdersController

In our OrdersController, we just enable scaffolding so we access the administrative panel.

<?php
class OrdersController extends AppController {
	var$scaffold="admin";
}
	
?>

Now it is time for the last controller – the UsersController.

class UsersController extends AppController {
	var$scaffold="admin";
	public$layout="main";
	public function beforeFilter() {

			parent::beforeFilter();
			$isAdmin=!empty($this->request->params['admin']);

			if ($isAdmin) {
				$this->layout="default";
			}

		
		}

We set scaffolding and the layout and give the default layout if the user is trying to access the admin panel.

public function admin_login() {
	$this->redirect(array(
	'controller'=>'offers',
	'action'=>'index',
	'admin'=>false
	));
}

We redirect users that are not admins to the offers/ controller since we do not want a special admin login panel. The admins can log in as normal users do.

Notice that we specify an admin key with false as value. If we do not specify that users will be redirected to /admin/offers which would redirect them to admin/users/login in an endless loop.

public function logout() {
	$this->Session->setFlash("You have been logged out!");
	$this->redirect($this->Auth->logout());
}

 

The logout method is easy, we do not need a View for it since we logout and redirect to the page we set that logged out users should go. We also send a one-time message that the user has been logged out before that.

public function register() {

		if ($this->request->is("post")) {
			$this->User->create();

			if ($this->User->save($this->request->data)) {
				
				$this->Session->setFlash("Account created. You may log in!");
				$this->redirect(array(
					'controller'=>'offers',
					'action'=>'index'
					));
			}
		}

	}

In our register method, we just save the data into the database and redirect if the save has been successful.

public function login() {
		if ($this->request->is("post")) {
		

			if ($this->Auth->login()) {
				$this->Session->setFlash("You have been logged in. You can now add offers and buy goods.");
				$this->redirect(array(
					'controller'=>'offers',
					'action'=>'index'
					));
			}

			else {

				$this->Session->setFlash("Wrong username or password.");

			}

		}	
	}

We are using CakePHP’s cool method $this->Auth->login() which attempts to login the user. It returns true if it manages to log him in with the credentials sent by POST and false if there was an error. If his credentials are correct, we send a one-time message and redirect to offerscontroller. Otherwise, we stay on the same page with a message that the username/password were incorrect.

Finally, here are the Views for these methods:

View/Users/Login.ctp

<?php

$this->start("page_content");

$flash = $this->Session->flash(); 

if (isset($flash) && !empty($flash)) : ?>
<div data-alert class="alert-box text-center">
<?php echo $flash; ?>
<a href="#"class="close">&times;</a>
</div>
<?php endif; ?>
<div class="panel text-center radius callout">
	<h2>Login with an existing account</h2>
</div>
<div class="row">
	<div class="medium-6 medium-offset-3 columns">
		<?php

		echo $this->Form->create("User",
			array('action'=> 'login'
			));

		echo $this->Form->input('username');
		echo $this->Form->input("password");

		echo $this->Form->end(array(
			'label' => 'Login',
			'class' => 'button medium round'
			));

			?>
	</div>
</div>


<?php $this->end(); ?>

We are using the CakePHP’s Form helper and just echo a login form, possible flash messages and we have some Foundation classes.

View/Users/register.ctp

<?php $this->start("page_content");
$flash=$this->Session->flash(); 

if (isset($flash) &&!empty($flash)) :?>
<div data-alert class="alert-box text-center">
<?php echo$flash; ?>
<a href="#" class="close">&times;</a>
</div>
<?php endif; ?>
<div class="panel radius">
<h2 class="text-center">Register in The Market </h1>
</div>
<div class="row">
<div class="medium-6 medium-offset-3">
<?php echo$this->Form->create("User");
echo $this->Form->input("username",
array("label"=>'Username:')
      );

echo $this->Form->input("password",
array("label"=>'Password:')
      );

echo $this->Form->input("full_name",
array("label"=>'Full name:')
      );

echo $this->Form->input("address",
array("label"=>'Address: ')
      );
echo $this->Form->end(
array('class'=>'button  medium radius success ',
'label'=>"Register"
        )
      );
?>
</div>
</div>

<?php$this->end(); ?>

It is pretty much the same as the login form so we shall not discuss it specifically.

I hope now you have turned from knowing nothing about CakePHP to being able to make your own CakePHP applications. And remember – read the documentation in http://cakephp.org/ or even better – they have a Cookbook which is more than 1000 pages long. You can download it from:

http://book.cakephp.org/2.0/_downloads/en/CakePHPCookbook.pdf

You can also read the documentation about Foundation, located at: http://foundation.zurb.com/docs/ as Twitter Bootstrap is not the only front-end framework out there.

Part 1: How to Build a Marketplace with CakePHP 2 & Foundation 1/6

Part 2: How to Build a Marketplace with CakePHP 2 & Foundation 2/6

Part 3: How to Build a Marketplace with CakePHP 2 & Foundation 3/6

Part 4: How to Build a Marketplace with CakePHP 2 & Foundation 4/6

Part 5: How to Build a Marketplace with CakePHP 2 & Foundation 5/6

Part 6: How to Build a Marketplace with CakePHP 2 & Foundation 6/6

Marketplace with CakePHP 2 & Foundation Demo & Download

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories:

5 responses to “How to Build a Marketplace with CakePHP 2 & Foundation 6/6”

  1. handoyo says:

    Thanks a lot for the tutorial.

  2. Arıkan says:

    Where to download and demo link ?

  3. thaw says:

    where can i download it?

  4. Theodis Butler says:

    i’ll be the first to admit, i don’t usually follow a tutorial no matter how awesome until i can check out the finished goods first. looks like a great article but I don’t want to follow the rainbow only to reach the end and there is a pot of bronze instead of gold. thank you for your contribution to the community.

Leave a Reply

Your email address will not be published. Required fields are marked *