I'm using Zend Framework in combination with Doctrine 2 and mongoDB.
So far so good.
Now I'm rewriting my custom validation class in order to check if a username already exists in the database. (This code worked fine with ORM and MySQL, but not now with ODM and mongoDB).
So my custom validation class looks like this:
<?php
class Project_Validate_UsernameUnique extends Zend_Validate_Abstract {
const USERNAME_EXISTS = '';
protected $_messageTemplates = array (
self::USERNAME_EXISTS => "'%value%' is taken. Please choose another username."
);
public function isValid($value) {
// setting value for the form
$this->_setValue($value);
// get the document manager and repository
$front = Zend_Controller_Front::getInstance();
$dm = $front->getParam('bootstrap')->getResource('odm');
$userRepository = $dm->getRepository('Entities\User');
$user = $userRepository->findOneBy(array('username' => $value));
// if an user was found, return false
if ($user) {
$this->_error(self::USERNAME_EXISTS);
return false;
}
return true;
}
}
But I get this error here:
Warning: file_put_contents(/Applications/XAMPP/xamppfiles/htdocs/project/application/models/Hydrators/EntitiesUserHydrator.php) [function.file-put-contents]: failed to open stream: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/project/library/Doctrine/ODM/MongoDB/Hydrator/HydratorFactory.php on line 343
I also tried findBy and without the array annotation (findByUsername or findOneByUsername), but still, either I get this error or somehow "nothing".
With ORM and MySQL it worked perfect, so where is the problem?
Thanks in advance!
Is your Hydrators folder writable by PHP?
Related
I am trying to save a relationship with the Laravel save method:
public function storeContact(Request $request)
{
$user = User::firstOrNew(['email' => $request->input('email')]);
$user->save();
$message = new App\Message([
'message' => $request->input('remarks')
]);
$user->message()->save($message);
}
var_dump($request->all) confirms both fields are available in the request.
All relations work. hasOne, belongsTo are configured in the models. The relation is saved like expected (but message field is empty)
When I var_dump($message), there are no attributes in the collection.
I already tried fillable and guarded on the models without any effect. These should not be necessary for the save method though because this uses a full Eloquent model instance.
What am I missing here??
I think I found the culprit.
When I use a __construct on a model it fails. When I instantiate a model with a __construct no variables are passes as attributes. Even if the __construct is empty.
Test with __construct method
class Message extends Model
{
protected $connection = 'system';
public function __construct()
{
}
// ...
}
$message = new App\Message(['remarks' => 'Test remarks']);
var_dump(message) // does NOT contain attributes!
Test2 without __construct method
class Message extends Model
{
protected $connection = 'system';
// ...
}
$message = new App\Message(['remarks' => 'Test remarks']);
var_dump(message) // does contain attributes!
This looks like a bug in Laravel to me.
I am new to Laravel. I was looking at the Eloquent relationships. I followed the documentation and defined my one to many relationship as:
// in the test model
public function questions()
{
return $this->hasMany('App\Question', 'test_name_id', 'test_id');
}
// in the question model
public function test()
{
return $this->belongsTo('App\Test', 'test_name_id', 'test_id');
}
Note that i have not followed the convention for naming the id's. So if I do this in the Tinker:
$test = App\Test::first();
$question = $test->questions;
It works fine. But if want the record any other than first like doing:
$test = App\Test::where(['test_id'=>'2'])->get();
$question = $test->questions;
It gives me this error:
PHP error: Trying to get property of non-object on line 1
Can any one please explain me what I am doing wrong here and how does this work properly?
Try ->first() instead of get(). get() returns array. Or use protected $primaryKey = 'test_id'; in test model and then ->find($id)
I'm trying to set up an authentication system with Laravel 4 with a Facebook login. I am using the madewithlove/laravel-oauth2 package for Laravel 4.
Of course, there is no password to add to my database upon a user loggin in with Facebook. I am, however, trying to check to see if a user id is in the database already to determine if I should create a new entity, or just log in the current one. I would like to use the Auth commands to do this. I have a table called "fans".
This is what I'm working with:
$fan = Fan::where('fbid', '=', $user['uid']);
if(is_null($fan)) {
$fan = new Fan;
$fan->fbid = $user['uid'];
$fan->email = $user['email'];
$fan->first_name = $user['first_name'];
$fan->last_name = $user['last_name'];
$fan->gender = $user['gender'];
$fan->birthday = $user['birthday'];
$fan->age = $age;
$fan->city = $city;
$fan->state = $state;
$fan->image = $user['image'];
$fan->save();
return Redirect::to('fans/home');
}
else {
Auth::login($fan);
return Redirect::to('fans/home');
}
Fan Model:
<?php
class Fan extends Eloquent {
protected $guarded = array();
public static $rules = array();
}
When I run this, I get the error:
Argument 1 passed to Illuminate\Auth\Guard::login() must be an instance of Illuminate\Auth\UserInterface, instance of Illuminate\Database\Eloquent\Builder given
EDIT: When I use: $fan = Fan::where('fbid', '=', $user['uid'])->first();
I get the error:
Argument 1 passed to Illuminate\Auth\Guard::login() must be an instance of Illuminate\Auth\UserInterface, null given, called in /Applications/MAMP/htdocs/crowdsets/laravel-master/vendor/laravel/framework/src/Illuminate/Auth/Guard.php on line 368 and defined
I do not know why it is giving me this error. Do you have suggestions on how I can make this work? Thank you for your help.
You have to implement UserInterface to your model for Auth to work properly
use Illuminate\Auth\UserInterface;
class Fan extends Eloquent implements UserInterface{
...
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
}
getAuthIdentifier and getAuthPassword are abstract method and must be implemented in you class implementing UserInterface
To login any user into the system, you need to use the User model, and I bet inherited classes will do the trick as well but I'm not sure.
Anyway, your Fan model does not associate with the User model/table in any way and that's a problem. If your model had a belong_to or has_one relationship and a user_id field then you could replace Auth::login($user) with Auth::loginUsingId(<some id>).
Original answer:
You are missing an extra method call: ->get() or ->first() to actually retrieve the results:
$fan = Fan::where('fbid', '=', $user['uid'])->first();
Alternatively, you can throw an exception to see what's going on:
$fan = Fan::where('fbid', '=', $user['uid'])->firstOrFail();
If you see different errors, update your question with those errors.
I am attempting to extend the Zend Framework Quickstart tutorial by trying to make an individual view for each guestbook entry, but I am missing something and keep getting errors like:
Trying to get property of non-object in C:\wamp\www\quickstart.local\application\views\scripts\guestbook\display.phtml
I get this when trying the following for my displayAction and my display.phtml:
//view
<p><?php echo $this->escape($this->entry->id); ?></strong> <a><?php echo $this->escape($this->entry->comment); ?></a><br>
<?php echo $this->escape($this->entry->email); ?></p>
//action
public function displayAction()
{
$id = $this->getRequest()->getParams('id');
$entry = new Application_Model_GuestbookMapper();
$this->view->entry = $entry->find($id);
}
And the find() function in the mapper is as is from the tutorial.
I have look all over the web and have only found tutorials that omit the quickstart guide's structure altogether. While they are all solid in their own right, I would like to find a solution to this. What am I doing wrong?
I am about mid-level with php and a beginner with zend framework. Please keep that in mind when responding.
If you're following the quickstart verboten, you'll want something like this
public function displayAction()
{
$id = $this->getRequest()->getParam('id');
$model = new Application_Model_Guestbook;
$mapper = new Application_Model_GuestbookMapper;
$mapper->find($id, $model);
if (null === $model->getId()) {
throw new Zend_Controller_Action_Exception(
sprintf('Guestbook entry %d not found', $id), 404);
}
$this->view->entry = $model;
}
in order to use GuestbookMapper with the Find() method you need to supply two items of information to the method, the id and an instance of Guestbook. The instance of guestbook is required because it has all the getters and setters mapper uses to generate the returned data.
//action updated
public function displayAction()
{
$id = $this->getRequest()->getParams('id');
$guestbook = new Application_Model_GuestBook();
$entry = new Application_Model_GuestbookMapper();
$this->view->entry = $entry->find($id, $guestbook);
}
for a detailed explaination of how this works check out chapter 9 of Survive the Deepend
I'm trying to set up a route in Zend Framework (version 1.11.11) in a routes.ini file, which would allow be to match the following url:
my.domain.com/shop/add/123
to the ShopController and addAction. However, for some reason the parameter (the number at the end) is not being recognized by my action. The PHP error I'm getting is
Warning: Missing argument 1 for ShopController::addAction(), called in...
I know I could set this up using PHP code in the bootstrap, but I want to understand how to do this type of setup in a .ini file and I'm having a hard time finding any resources that explain this. I should also point out that I'm using modules in my project. What I've come up with using various snippets found here and there online is the following:
application/config/routes.ini:
[routes]
routes.shop.route = "shop/add/:productid/*"
routes.shop.defaults.controller = shop
routes.shop.defaults.action = add
routes.shop.defaults.productid = 0
routes.shop.reqs.productid = \d+
Bootstrap.php:
...
protected function _initRoutes()
{
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/routes.ini', 'routes');
$router = Zend_Controller_Front::getInstance()->getRouter();
$router->addConfig( $config, 'routes' );
}
...
ShopController.php
<?php
class ShopController extends Egil_Controllers_BaseController
{
public function indexAction()
{
// action body
}
public function addAction($id)
{
echo "the id: ".$id;
}
}
Any suggestions as to why this is not working? I have a feeling I'm missing something fundamental about routing in Zend through .ini files.
Apparently I'm more rusty in Zend than I thought. A few minutes after posting I realized I'm trying to access the parameter the wrong way in my controller. It should not be a parameter to addAction, instead I should access it through the request object inside the function:
correct addAction in ShopController:
public function addAction()
{
$id = $this->_request->getParam('productid');
echo "the id: ".$id;
}
I also realized I can simplify my route setup quite a bit in this case:
[routes]
routes.shop.route = "shop/:action/:productid"
routes.shop.defaults.controller = shop
routes.shop.defaults.action = index