Cannot save POST items to database with Phalcon framework - php

Controller:
class PeopleController extends \Phalcon\Mvc\Controller{
public function indexAction(){
}
public function CreatePersonAction(){
$person = new people();
$person->firstName=$this->request->getPost("firstName");
$person->surname=$this->request->getPost("surname");
$person->telephone=$this->request->getPost("telephone");
$person->email=$this->request->getPost("email");
$person->city=$this->request->getPost("city");
$person->country=$this->request->getPost("country");
$person->save();
if ($person) {
echo"Successfully Registered User!";
} else {
echo "Sorry, the following problems were generated: ";
foreach ($person->getMessages() as $message) {
echo $message->getMessage(), "<br/>";
}
}
}
}
Model:
<?php
class People extends \Phalcon\Mvc\Model{
}
I have tried implementing the getSource() method into the model as the phalcon docs suggest that but still not getting the desired output of saving the POST items to the database

Try this:
<?php
use Phalcon\Mvc\Controller as PhController;
class PeopleController extends PhController
{
public function IndexAction()
{
//When no view(aka template) is used you should disable the view rendering
//Otherwise the output buffer can get overwritten and your echoes won't display
$this->view->disable();
echo "<h1>Index Action!</h1>";
}
public function CreatePersonAction()
{
$this->view->disable();
if($this->request->isPost()) {
$dataSent = $this->request->getPost();
$person = new People();
$person->firstName = $dataSent["firstName"]
$person->surname = $dataSent["surname"];
$person->telephone = $dataSent["telephone"];
$person->email = $dataSent["email"];
$person->city = $dataSent["city"];
$person->country = $dataSent["country"];
$savedSuccessfully = $person->save();
if($savedSuccessfully) {
echo "Successfully Registered User!";
} else {
$messages = $person->getMessages();
echo "Sorry, the following problems were generated: ";
foreach ($messages as $message) {
echo "$message <br/>";
}
}
} else {
echo "The request method should be POST!";
}
}
}
Also, add this code to your main index.php (just before Phalcon\Mvc\Application->handle()):
$debug = new \Phalcon\Debug();
$debug->listen();
With this you'll get better error messages, so you can check if your DB settings are OK. Also remember that Phalcon only works with the database schema passively, that means, all tables and fields should already exist to the Model get stored, Phalcon just use the tables and never create them.

Related

Php variable accessed from class in another file empty

I am new to php and I am trying to program an app that uses php as backend. I don't really have an error in my code but I can't figure something out I have search but nothing has helped.there maybe be a solution but I can't find it.
I have 3 php file
Index.php
<?php
include "methods.php";
$user=new user();
if (isset($_GET["action"])) {
// code...
switch ($_GET["action"]) {
case 'login':
// code...
$user->login();
break;
default:
// code...
echo("error 404");
break;
}
} else {
// code...
echo("error 404");
}
?>
Methods.php
<?php
include "extra.php";
class user {
public function login() {
$input = new input();
$error = "fucked";
$validationresult = json_decode($input->validateinput(), true);
echo var_dump($validationresult);
$validated = $validationresult["validated"];
if ($validated) {
// code...
echo ("yes");
} else {
echo var_dump($validationresult);
// echo json_encode(($validationresult["error"]));
}
}
}
?>
extra.php
<?php
class input {
public $password;
public $status;
public $validated;
public function __construct()
{
// code...
}
public function validateinput () {
$password = $_GET["password"];
$this-> $status = "red";
$this->$validated = false;
echo($this-> $status);
return json_encode('{
"validated":'.$this->get_validate().',
"error":{
"status":"'.$this->$status.'",
"username":"ok",
"password":"cannot be more than 5"
}
}');
}
public function get_validate(){
return $this->$validated;
}
}
?>
As you can see in index.php I called $user->login();
From methods.php which echos JSON $input->validateinput() from file extra.php.
But
"validated":'.$this->get_validate().'
And
"status":"'.$this->$status.'
From extra.php
Is empty
I don't why it is empty and the internet confuses me more.
I am sorry for my grammatical mistakes as I am typing from a mobile phone and English isn't my first language.

PHP extends namespace\class unknown error

This is my parent class code: \core\controller\controlmaster
<?php
namespace core\controller;
class controlmaster{
private $model_base = null;
//public function __construct(){
//always start session for any loaded controller
//session_start();
//}
public function _loadModels($models){
$file = dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR.$this->model_base.$models.".php";
$file_alloc = str_replace("\\","/",$file);
if(file_exists($file_alloc)){
require($file_alloc);
$models_name = $this->model_base.$models;
return new $models_name();
}
}
public static function _setModelBase($model_location){
$this->model_base = $model_location;
}
}
?>
and this is my controller page for application : \applications\controller\index
<?php
namespace applications\controllers;
use core\configuration\configloader as config;
class index extends \core\controller\controlmaster{
public $config;
public function __construct(){
$this->config = new config;
$this->config->_parsePHP("j3mp_setting.php");
parent::_setModelBase($this->config->settings['app_model_base']); // Error doesn't appear when i comment this function
echo "This is main page and this is config for model app base : {$this->config->settings['base_url']}";
}
}
?>
This is core\configuration\configloader:
<?php
namespace core\configuration;
class configloader{
//Contains setting informations
public $inisettings;
public $settings;
public function _parseINI($file,$section){
$section = empty($section) ? false : true;
$file = __DIR__.DIRECTORY_SEPARATOR.$file;
if(file_exists($file)){
$parse = parse_ini_file($file,$section);
$this->inisettings = $parse;
}else{
throw new core\errorhandler\exception("File {$file} is not found in our system. Please contact administrator for details.","configloader");
}
}
public function _parsePHP($file){
$file = __DIR__.DIRECTORY_SEPARATOR.$file;
if(file_exists($file)){
$settings = array();
include($file);
$this->settings = $settings;
}else{
throw new core\errorhandler\exception("File {$file} is not found in our system. Please contact administrator for details.","configloader");
}
}
}
?>
When i comment "parent::_setModelBase(...)" code, the error disappear and the browser successfully print "This is main page and this is config for model app base : http://iosv3.net/". I think the error come from \core\controller\controlmaster, but I don't know how to fix that? I always try to edit the file (\core\controller\controlmaster) but notting happens... If error occured, the message ("This is main page ...") doesn't come out... Could you show me where is the error come from? Thanks...

Php Memcache Design Patterns issue

For a small home project I am working on I have been looking for OO design patterns for Memcache implementation, but so far haven't found something I feel fits, so maybe my approach is wrong.
I have a DB connection class and an baseModel class so I want to implement caching on the baseModel where appropriate.
I have implemented the Database connection and the Cacher as Singlton patterns.
I cannot seem to get the Cacher class to read the data or trigger the echo "<p>Getting from cache"; line after I refresh the page on the base Model "loadFromDb" function
Here are the classes:
class Cacher {
protected static $cacher = null;
private static $settings;
public static function getCache() {
if (self::$cacher != null) {
return self::$cacher;
}
try {
self::$settings = parse_ini_file("./configs/main.ini");
self::$cacher = new Memcache();
self::$cacher->connect(
self::$settings['cache_server_host']
, self::$settings['cache_server_port']
);
} catch (Exception $e) {
// TODO log error and mitigate..
echo "Error connecting memcache";
die();
}
var_dump(self::$cacher->getstats());
return self::$cacher;
}
public static function getData($key) {
if (self::$cacher == null) {
self::getCache();
}
return self::$cacher->get($key);
}
public static function setData($key, $data, $expire = 0) {
if (self::$cacher == null) {
self::getCache();
}
if (self::$cacher)
return self::$cacher->set($key, $data, MEMCACHE_COMPRESSED, $expire);
}
}
class ModelBase {
protected $fields = array();
protected $class = null;
function __construct($class_name) {
$this->class = $class_name;
$this->fields = Database::getFields($class_name);
}
public function loadFromDB($id, $fromCache = true) {
$key = "loadFromDB_{$this->class}_{$id}";
if ($fromCache) {
$data = Cacher::getData($key);
if ($data) {
echo "<p>Getting from cache";
return unserialize($data);
} else {
echo "<p>No cache data. going to DB";
}
}
$values = Database::loadByID($this->class, $this->fields[0], $id);
foreach ($values as $key => $val) {
$this->$key = $val;
}
$dataSet = Cacher::setData($key, serialize($this));
echo "<p>Data set = $dataSet";
}
}
Memcache service is running and I can read data directly back if I read the cache directly after I write it, but what I want is to read the data from the DB only the first time the page loads, after that use the cache....
Any comments welcome...
Try doing it like (let the result of the cache decide if you should query the db):
<?php
public function loadFromDB($id) {
$key = "loadFromDB_{$this->class}_{$id}";
//query cache
$data = Cacher::getData($key);
//is it found
if (!empty($data)) {
//echo "<p>Getting from cache";
return unserialize($data);
}
//no so lest query db
else {
//echo "<p>No cache data. going to DB";
$values = Database::loadByID($this->class, $this->fields[0], $id);
foreach ($values as $key => $val) {
$this->$key = $val;
}
//store it in cache
//$dataSet = Cacher::setData($key, serialize($this));
$dataSet = Cacher::setData($key, serialize($values));//<<store the db result not the class
}
//echo "<p>Data set = $dataSet";
return unserialize($dataSet);
}
?>

issue with incrementing a variable in cakephp (basics)

Basically this is just a guessing game so that I can learn the ins and outs of cake.
I'm trying to keep track of the users number of guesses on every page reload (using a variable name $user_loop). When I try to increment it, it stays static or only increments by one and stops. I've placed the increment snippet in my view also to only receive the same results. Any help would be great.
<?php
class GuessController extends AppController {
public $uses = array();
function beforeFilter() {
if (!$this->Session->check('Random.Num')) {
$this->Session->write('Random.Num', rand(1, 9));
}
}
function create() {
if ($this->request->is('post', 'put')) {
$rn = $this->Session->read('Random.Num');
$user_guess = $this->request->data['Guess']['guess'];
$this->set('user_guess', $user_guess);
$user_loop++ // <- Also getting undefined variable here
echo $user_loop; //for testing
if ($rn == $user_guess) {
echo 'Cashe Cleared';
$this->Session->delete('Random');
}
}
}
}
?>
Try this :
<?php
class GuessController extends AppController {
public $uses = array();
function beforeFilter() {
if (!$this->Session->check('Random.Num')) {
$this->Session->write('Random.Num', rand(1, 9));
}
if(!$this->Session->check('user_loop')) {
$this->Session->write('user_loop',0);
}
}
function create() {
if ($this->request->is('post', 'put')) {
$rn = $this->Session->read('Random.Num');
$user_guess = $this->request->data['Guess']['guess'];
$this->set('user_guess', $user_guess);
$user_loop = $this->Session->read('user_loop')+1;
echo $user_loop; //for testing
$this->Session->write('user_loop',$user_loop);
if ($rn == $user_guess) {
echo 'Cash Cleared';
$this->Session->delete('Random');
}
}
}
}
?>

Using PHP Activerecord Finders in Classes

I'm trying to test if a record exists with the following code using PHP Activerecord:
class User extends ActiveRecord\Model {
public function user_exists() {
$user = User::find_by_email($this->email);
if ( $user ) {
return true;
} else {
return false;
}
}
}
$user = new User();
$user->email = "test#email.com";
if ( $user->user_exists() ) {
echo "user exists";
} else {
echo "no user";
}
For some reason, I'm getting a 'Call to undefined method: find_by_email' error. What am I doing wrong?
Try the exists method:
User::exists(array('email' => $this->email));
Which is faster because it only checks for existence but does not fetch the data.
Or even better; use model validations:
http://www.phpactiverecord.org/projects/main/wiki/Validations#validates_uniqueness_of

Categories