Why not receving email address using Google_Oauth2Service in php? - php

Does anyone know how I can get the user email address?
My code is below:
require_once("sm/google/Google_Client.php");
require_once("sm/google/contrib/Google_PlusService.php");
require_once("sm/google/contrib/Google_Oauth2Service.php");
include_once("ErrorReporting.php");
$objError = new ErrorReporting();
$client = new Google_Client();
$client->setApplicationName("myproject");
//$client->setHttpClient($httpClient);
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri($callbackurl);
$client->setDeveloperKey(GOOGLE_API_KEY);
$client->setAccessType("online");
$client->setApprovalPrompt("auto");
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
$oauth2Service = new Google_Oauth2Service($client);
$plus = new Google_PlusService($client);
$userinfo = $oauth2Service->userinfo;
print_r($userinfo->get());
if (isset($_GET['code'])) {
try {
$client->authenticate();
} catch(Exception $e) {
$objError->reportError("Error! while authenticate through google",$e ,'dev');
}
$token = $client->getAccessToken();
try {
$userProfile = $plus->people->get("me");
print_r($userProfile);
exit();
} catch(Exception $e) {
//echo $e;
$objError->reportError("Error! while login through google",$e ,'dev');
}
$id = $userProfile['id'];
return array(
'user' => $id,
'network' => 'google',
'userprofile' => $userProfile,
'token' => $token,
'loginUrl' => null,
'logoutUrl' => null
);
} else {
$authUrl = $client->createAuthUrl();
return array(
'user' => 0,
'network' => 'google',
'userprofile' => $userProfile,
'token' => null,
'loginUrl' => $authUrl,
'logoutUrl' => null
);
}
}
So not sure how I can get the email address using google oauth2service. As I tried to access it but no error appearing on screen but also no email address is fatched. I looked at the contrib/Google_Oauth2Service.php class file and don't find the get() method so not sure what I am missing here.
Following two line of code is not returning any email information:
$userinfo = $oauth2Service->userinfo;
print_r($userinfo->get());
My PHP version is 5.3
My Google_Oauth2Service.php file looks like below:
<?php
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "userinfo" collection of methods.
* Typical usage is:
* <code>
* $oauth2Service = new Google_Oauth2Service(...);
* $userinfo = $oauth2Service->userinfo;
* </code>
*/
class Google_UserinfoServiceResource extends Google_ServiceResource {
/**
* (userinfo.get)
*
* #param array $optParams Optional parameters.
* #return Google_Userinfo
*/
public function get($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Google_Userinfo($data);
} else {
return $data;
}
}
}
/**
* The "v2" collection of methods.
* Typical usage is:
* <code>
* $oauth2Service = new Google_Oauth2Service(...);
* $v2 = $oauth2Service->v2;
* </code>
*/
class Google_UserinfoV2ServiceResource extends Google_ServiceResource {
}
/**
* The "me" collection of methods.
* Typical usage is:
* <code>
* $oauth2Service = new Google_Oauth2Service(...);
* $me = $oauth2Service->me;
* </code>
*/
class Google_UserinfoV2MeServiceResource extends Google_ServiceResource {
/**
* (me.get)
*
* #param array $optParams Optional parameters.
* #return Google_Userinfo
*/
public function get($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Google_Userinfo($data);
} else {
return $data;
}
}
}
/**
* Service definition for Google_Oauth2 (v2).
*
* <p>
* Lets you access OAuth2 protocol related APIs.
* </p>
*
* <p>
* For more information about this service, see the
* API Documentation
* </p>
*
* #author Google, Inc.
*/
class Google_Oauth2Service extends Google_Service {
public $userinfo;
public $userinfo_v2_me;
/**
* Constructs the internal representation of the Oauth2 service.
*
* #param Google_Client $client
*/
public function __construct(Google_Client $client) {
$this->servicePath = '';
$this->version = 'v2';
$this->serviceName = 'oauth2';
$client->addService($this->serviceName, $this->version);
$this->userinfo = new Google_UserinfoServiceResource($this,
$this->serviceName, 'userinfo', json_decode('{"methods": {"get": {"id": "oauth2.userinfo.get", "path": "oauth2/v2/userinfo", "httpMethod": "GET", "response": {"$ref": "Userinfo"}, "scopes": ["https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"]}}}', true));
$this->userinfo_v2_me = new Google_UserinfoV2MeServiceResource($this, $this->serviceName, 'me', json_decode('{"methods": {"get": {"id": "oauth2.userinfo.v2.me.get", "path": "userinfo/v2/me", "httpMethod": "GET", "response": {"$ref": "Userinfo"}, "scopes": ["https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"]}}}', true));
}
}
class Google_Tokeninfo extends Google_Model {
public $access_type;
public $audience;
public $email;
public $expires_in;
public $issued_to;
public $scope;
public $user_id;
public $verified_email;
public function setAccess_type( $access_type) {
$this->access_type = $access_type;
}
public function getAccess_type() {
return $this->access_type;
}
public function setAudience( $audience) {
$this->audience = $audience;
}
public function getAudience() {
return $this->audience;
}
public function setEmail( $email) {
$this->email = $email;
}
public function getEmail() {
return $this->email;
}
public function setExpires_in( $expires_in) {
$this->expires_in = $expires_in;
}
public function getExpires_in() {
return $this->expires_in;
}
public function setIssued_to( $issued_to) {
$this->issued_to = $issued_to;
}
public function getIssued_to() {
return $this->issued_to;
}
public function setScope( $scope) {
$this->scope = $scope;
}
public function getScope() {
return $this->scope;
}
public function setUser_id( $user_id) {
$this->user_id = $user_id;
}
public function getUser_id() {
return $this->user_id;
}
public function setVerified_email( $verified_email) {
$this->verified_email = $verified_email;
}
public function getVerified_email() {
return $this->verified_email;
}
}
class Google_Userinfo extends Google_Model {
public $birthday;
public $email;
public $family_name;
public $gender;
public $given_name;
public $hd;
public $id;
public $link;
public $locale;
public $name;
public $picture;
public $timezone;
public $verified_email;
public function setBirthday( $birthday) {
$this->birthday = $birthday;
}
public function getBirthday() {
return $this->birthday;
}
public function setEmail( $email) {
$this->email = $email;
}
public function getEmail() {
return $this->email;
}
public function setFamily_name( $family_name) {
$this->family_name = $family_name;
}
public function getFamily_name() {
return $this->family_name;
}
public function setGender( $gender) {
$this->gender = $gender;
}
public function getGender() {
return $this->gender;
}
public function setGiven_name( $given_name) {
$this->given_name = $given_name;
}
public function getGiven_name() {
return $this->given_name;
}
public function setHd( $hd) {
$this->hd = $hd;
}
public function getHd() {
return $this->hd;
}
public function setId( $id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setLink( $link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setLocale( $locale) {
$this->locale = $locale;
}
public function getLocale() {
return $this->locale;
}
public function setName( $name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setPicture( $picture) {
$this->picture = $picture;
}
public function getPicture() {
return $this->picture;
}
public function setTimezone( $timezone) {
$this->timezone = $timezone;
}
public function getTimezone() {
return $this->timezone;
}
public function setVerified_email( $verified_email) {
$this->verified_email = $verified_email;
}
public function getVerified_email() {
return $this->verified_email;
}
}
Thanks

I don't know how you're using this but I've tried with v1-master branch of google apiclient and I'm able to fetch user's email address
$client = new Google_Client();
$client->setApplicationName('Login to Test Project');
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri(GOOGLE_REDIRECT_URL);
$client->addScope(['email', 'profile']);
if (isset($_GET['code'])) {
try {
$token = $client->authenticate($_GET['code']);
$Oauth = new Google_Service_Oauth2($client);
$info = $Oauth->userinfo->get();
print_r($info);
} catch (Exception $exception) {
print_r($exception->getMessage());
}
} else {
$authUrl = $client->createAuthUrl();
header('Location: '.$authUrl);
}
Please share your composer.json file, so that I can try with your configurations to provide a better solution.

I noticed a couple things on your end that could be causing you some grief. Your order of operations seems to be reversed. You shouldn't be calling this:
$userinfo = $oauth2Service->userinfo;
print_r($userinfo->get());
before this:
$client->authenticate();
Also, you should be sending the code along with the client.
So, something like this should get you some proper output:
if (isset($_GET['code'])) {
$code = $_GET['code'];
try {
$client->authenticate($code);
} catch(Exception $e) {
$objError->reportError("Error! while authenticate through google",$e ,'dev');
}
$userinfo = $oauth2Service->userinfo;
print_r($userinfo->get());
}
Give that a try, and then let us know if you're on the right track. Also, Google Plus has been deprecated, so I would recommend you don't use those libraries any longer.

Related

Uncaught Error: Using $this when not in object context in /opt/lampp/htdocs/yii2-keycloak-main/src/example/views/site/index.php:9

I've got a problem. In my code I'm using index.php.
index.php
$this->title = 'home';
?>
<div class="site-index">
<div class="jumbotron">
<?php echo Yii::getVersion(); ?>
</div>
</div>
keycloak.php
<?php
namespace limefamily\OpenIdConnect;
use yii\authclient\Collection;
use yii\authclient\InvalidResponseException;
use Yii;
use yii\authclient\OAuthToken;
use yii\authclient\OpenIdConnect;
use yii\base\InvalidConfigException;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\redis\Connection;
/**
* Keycloak
* #package limefamily\OpenIdConnect
* #property string $logoutUrl
* #property Connection $redis
*/
class Keycloak extends OpenIdConnect
{
public $logoutUrl;
public $redis;
const SESSION_STATE_KEY_PREFIX = 'session_state_';
/**
* #throws InvalidConfigException
*/
public function init()
{
if (empty($this->redis)) {
throw new InvalidConfigException("redis must be set");
}
if (empty($this->logoutUrl)) {
throw new InvalidConfigException('logoutUrl must be set');
}
if (!($this->redis instanceof Connection)) {
$this->redis = Yii::$app->get($this->redis);
}
parent::init();
}
/**
* Initializes authenticated user attributes.
* #return array|null
* #throws HttpException
*/
protected function initUserAttributes()
{
$token = $this->getAccessToken()->getToken();
return $this->loadJws($token);
}
protected function defaultName()
{
return 'keycloak';
}
protected function defaultTitle()
{
return 'Keycloak';
}
public static function refreshToken(){
if (!Yii::$app->user->getIsGuest()) {
$client = self::getInstance();
if ($client->getSsoSession() != null) {
try {
if ($client->getAccessToken()->getIsExpired()) {
$client->refreshAccessToken($client->getAccessToken());
}
}catch (InvalidResponseException $e) {
$client->removeSsoSession();
Yii::$app->user->logout();
}
} else {
Yii::$app->user->logout();
}
}
}
private static function getSessionStateKey($sessionState) {
return self::SESSION_STATE_KEY_PREFIX . $sessionState;
}
private function removeSsoSession() {
$state = $this->getSessionState();
if (!empty($state)) {
$this->redis->del(self::getSessionStateKey($state));
}
}
private function getSsoSession() {
$state = $this->getSessionState();
if (!empty($state)) {
return $this->redis->get(self::getSessionStateKey($state));
}
return null;
}
public function setSsoSession() {
$state = $this->getSessionState();
if (!empty($state)) {
$this->redis->set(self::getSessionStateKey($state), Yii::$app->session->getId());
}
}
public function getSessionState(){
/** #var OAuthToken $token */
$token = $this->getState('token');
return $token->getParam('session_state');
}
/**
* #return Keycloak
* #throws NotFoundHttpException
* #throws InvalidConfigException
*/
public static function getInstance() {
/* #var $collection Collection */
$collection = Yii::$app->get('authClientCollection');
if (!$collection->hasClient('keycloak')) {
throw new NotFoundHttpException("Unknown auth client 'keycloak");
}
/** #var Keycloak $client */
$client = $collection->getClient('keycloak');
return $client;
}
public static function logout($redirect) {
if (!Yii::$app->user->getIsGuest()) {
$client = self::getInstance();
$client->removeSsoSession();
$logoutUrl = $client->logoutUrl. "?redirect_uri=". urlencode($redirect);
Yii::$app->user->logout();
return Yii::$app->response->redirect($logoutUrl);
}
return Yii::$app->response->redirect($redirect);
}
/**
* #param $token
* #return array
* #throws HttpException
*/
public function loadAndVerifyLogoutToken($token) {
return $this->loadJws($token);
}
}
I am using limefamily plugin for keycloak integration.
This error is reported - how can I remove this error?
Fatal error: Uncaught Error: Using $this when not in object context in
/opt/lampp/htdocs/yii2-keycloak-main/src/example/views/site/index.php:9
Stack trace: #0 {main} thrown in
/opt/lampp/htdocs/yii2-keycloak-main/src/example/views/site/index.php
on line 9

php class method within method

If I want to access the public method, I can do that easily. But if I want to access the property within method, what should I do, and is it recommended??
Can I do something like this in php?
class Auth {
public function check($user = false){
$project = false; //make it somehow public
if($user == 'user1'){
$this->project = 1;
}
}
}
and than in some other place
$auth = new Auth();
$auth->check('user1')->project;
Just so you people know its possible here is the Zend framework code from
Zend-Authentication
if ($result->isValid()) {
$this->getStorage()->write($result->getIdentity());
}
I believe your question is basically regarding Fluent Interfaces or Method Chaining in conjunction with the magic method __get
Attempting to run this:
<?php
class Auth {
public function check($user = false){
$project = false; //make it somehow public
if($user == 'user1'){
$this->project = 1;
}
}
}
$auth = new Auth();
$auth->check('user1')->project;
Results in:
Notice: Trying to get property of non-object in /in/Hi5Rc on line 13
because $auth->check('user1') returns NULL (or void) and NULL doesn't have a project property.
The first thing we require is for $auth->check('user1') to return something useful. Given that $project is a boolean and $this->project is an integer, it makes the most sense to just return $project and get the value.
<?php
class Auth {
public function check($user = false){
$project = false; //make it somehow public
if($user == 'user1'){
$this->project = 1;
}
return $project;
}
}
$auth = new Auth();
print_r($auth->check('user1'));
which results in :
bool(false)
But that doesn't address your question about how to fluently access a nonpublic field or parameter.
It appears that you are operating under the misconception that these projects are taking method scoped variables like $project in your check() class and making them accessible. They are not.
Not even in your example of the Zend-Authentication.
The field $storage itself is protected, but it has public (fluent) getters/setters.
So, $this->getStorage() returns an instance of new Storage\Session() which has a public write().
Thus $this->getStorage()->write() works.
So lets take your example class and modify it a bit to demonstrate.
<?php
class Project{
/**
* #var string
*/
private $name;
/**
* #var bool
*/
private $active;
/**
* #var string
*/
private $description;
public function __construct($name = 'Default', $active = false, $description = '')
{
$this->name = $name;
$this->active = $active;
$this->description = $description;
}
/**
* #param string $name
*
* #return Project
*/
public function setName(string $name): Project
{
$this->name = $name;
return $this;
}
/**
* #param bool $active
*
* #return Project
*/
public function setActive(bool $active): Project
{
$this->active = $active;
return $this;
}
/**
* #param string $description
*
* #return Project
*/
public function setDescription(string $description): Project
{
$this->description = $description;
return $this;
}
/**
* #return string
*/
public function getName(): string
{
return $this->name;
}
/**
* #return bool
*/
public function isActive(): bool
{
return $this->active;
}
/**
* #return string
*/
public function getDescription(): string
{
return $this->description;
}
public function toArray(){
return [
'name' => $this->name,
'active' => $this->active,
'description' => $this->description
];
}
public function toJson(){
return json_encode($this->toArray());
}
public function __toString()
{
return $this->toJson();
}
}
class Auth {
/**
* #var Project
*/
private $project;
public function __construct($project = Null)
{
$this->project = is_null($project)? new Project() : $project;
}
public function check($user = false){
if($user == 'user1'){
$this->project->setName("Project: $user")->setActive(true)->setDescription("This project belongs to $user");
}
return $this;
}
/**
* #param Project $project
*
* #return Auth
*/
public function setProject(Project $project): Auth
{
$this->project = $project;
return $this;
}
/**
* #return Project
*/
public function getProject(): Project
{
return $this->project;
}
}
$auth = new Auth();
echo $auth->check('user1')->getProject();
now results in:
{"name":"Project: user1","active":true,"description":"This project
belongs to user1"}
However, you wanted to access the private field as if it were a public field without using a defined getter/setter. So lets make some more changes to the Auth class.
class Auth {
/**
* #var Project[]
*/
private $private_project;
public function __construct($project = Null)
{
$this->private_project = is_null($project)? new Project() : $project;
}
public function check($user = false){
if($user == 'user1'){
$this->private_project->setName("Project: $user")->setActive(true)->setDescription("This project belongs to $user");
}
return $this;
}
public function __get($name)
{
if ($name === 'project'){
return $this->private_project;
}
}
}
Now you can fluently access the field as you requested:
$auth = new Auth();
echo $auth->check('baduser')->project;
echo "\n";
echo $auth->check('user1')->project;
results in:
{"name":"Default","active":false,"description":""}
{"name":"Project: user1","active":true,"description":"This project belongs to user1"}
Laravel's Eloquent models make great use of the __get()function for accessing model fields dynamically. Laravel also makes great use of the __call() magic method for fluency.
I hope that helps bring some clarity.
class Auth
{
protected $project;
public function __constructor($project = false)
{
$this->project = $project;
}
public function check($user = false)
{
if($user == 'user1')
{
$this->project = 1;
}
return $this;
}
public function project()
{
return $this->project;
}
}
then you can do the following:
$auth = new Auth();
$auth->check('user1')->project(); // returns 1
or if you want you can also set another default value for the $projectin the constructor
$auth = new Auth($other_default_value);
$auth->check('user2')->project(); // returns $other_default_value
If you don't want to create extra class properties and "preserve method chaining", what about yield?
class Auth
{
public function check($user = false)
{
$project = false; // make it somehow public
if($user === 'user1'){
(yield 'project' => $project); // making it public
}
return $this;
}
}
Later on you can discover it as follows:
$array = iterator_to_array($auth->check($user));
// array(1) { ["project"] => bool(false) }
But for this to use you won't be able to use method chaining, bec. you need to retrieve generator anyway, so better to revise approach for discovering the $project.
<?php
class Auth
{
public $project;
public function check($user = false)
{
$this->project = false;//make it somehow public
if ($user == 'user1') {
$this->project = 1;
}
return $this;
}
}
$auth = new Auth();
var_dump($auth->check('user1')->project);
This will return you 1. The local variables defined in function are only accessbile inside the function not outside hence you need to define them globally
$project is a local variable in your case, visible within the scope of the check method. You could define it as a member:
class Auth {
public $project = false;
public function check($user = false){
if($user == 'user1'){
$this-project = 1;
}
}
}
However, it is recommendable to make the member public and reach it via a getter, which will check whether it was initialized and if not, initialize it:
class Auth {
private $project = false;
public getProject($user = false) {
if ($this->project === false) {
check($user);
}
return $this->project;
}
public function check($user = false){
if($user == 'user1'){
$this-project = 1;
}
}
}
You will need to add it as a class variable:
class Auth {
public $project = false;
public function check($user = false) {
if($user == 'user1'){
$this->project = 1;
}
}
}
The property is then available as follows:
$auth = new Auth ();
$auth->check ('user1');
echo $auth->project; // 1

Symfony2 custom Authenticator do something when not authenticated

How to manage Full authentication is required to access this resource.?
I want to redirect user when he is not authenticated.
I have custom uthenticater which authenticate user depending on session data, and i want to redirect user when hes not authenticatet.
My authenticator class:
/**
* #Service("sso_authenticator")
*/
class SsoAuthenticator implements SimplePreAuthenticatorInterface
{
/**
* #var SsoUserProvider
*/
protected $userProvider;
/**
* #InjectParams({
* "userProvider" = #Inject("sso_user_provider")
* })
*/
public function __construct(SsoUserProvider $userProvider)
{
$this->userProvider = $userProvider;
}
public function createToken(Request $request, $providerKey)
{
$user = $request->getSession()->get('sso_user');
if (!$user) {
throw new BadCredentialsException('No user found');
}
return new PreAuthenticatedToken(
'anon.', $user, $providerKey
);
}
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
{
$user = $token->getCredentials();
if (!is_array($user)) {
$user = $token->getUser();
}
if (!$user) {
throw new AuthenticationException('User does not exist.');
}
$ssoUser = $this->userProvider->loadUser($user);
return new PreAuthenticatedToken(
$ssoUser, $user, $providerKey, $ssoUser->getRoles()
);
}
public function supportsToken(TokenInterface $token, $providerKey)
{
return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
}
}
i set the login path to logout path like this:
secured_area:
form_login:
login_path : main_user_logout
then i wrote custom logout handler:
/**
* #Service("sso_authentication_handler")
*/
class SsoAuthenticationHandler implements LogoutSuccessHandlerInterface
{
/**
* #var Router
*/
private $router;
/**
* #var array
*/
protected $ssoUrls;
/**
* #InjectParams({
* "ssoUrls" = #Inject("%wordpress_sso%"),
* "router" = #Inject("router")
* })
*/
public function __construct(array $ssoUrls, Router $router)
{
$this->ssoUrls = $ssoUrls;
$this->router = $router;
}
public function onLogoutSuccess(Request $request)
{
$locale = $request->getLocale();
if ($locale === 'pl') {
$url = $this->ssoUrls[$locale];
} else {
$url = $this->ssoUrls['en'];
}
$url .= '?returnUrl=' . $this->router->generate('main');
return new RedirectResponse($url);
}
}
so with this combination i achive behavior like when youser is not authenticated or when he logout i will redirect him to other site to login, in my example to wordpress.

Update a record through model in zend framework

I am having a model and would need to update the record. every time $count ($count = $post->save()) is being NULL. how is it possible to know whether this record saved or not. if saved, i want to display the following message 'Post updated' and if not the other message 'Post cannot update'.
This is always going to the else port. how can i know model updated correctly or not?
$post = new Application_Model_Post($form->getValues());
$post->setId($id);
$count = $post->save();
//var_dump($count); exit;
if ($count > 0) {
$this->_helper->flashMessenger->addMessage('Post updated');
} else {
$this->_helper->flashMessenger->addMessage('Post cannot update');
}
Application_Model_Post code is as below,
class Application_Model_Post
{
/**
* #var int
*/
protected $_id;
/**
* #var string
*/
protected $_title;
/**
* #var string
*/
protected $_body;
/**
* #var string
*/
protected $_created;
/**
* #var string
*/
protected $_updated;
/**
* #var Application_Model_PostMapper
*/
protected $_mapper;
/**
* Class Constructor.
*
* #param array $options
* #return void
*/
public function __construct(array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
}
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key=> $value) {
$method = 'set'.ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setId($id)
{
$this->_id = $id;
return $this;
}
public function getId()
{
return $this->_id;
}
public function setTitle($title)
{
$this->_title = (string) $title;
return $this;
}
public function getTitle()
{
return $this->_title;
}
public function setBody($body)
{
$this->_body = $body;
return $this;
}
public function getBody()
{
return $this->_body;
}
public function setCreated($ts)
{
$this->_created = $ts;
return $this;
}
public function getCreated()
{
return $this->_created;
}
/**
* Set data mapper.
*
* #param mixed $mapper
* #return Application_Model_Post
*/
public function setMapper($mapper)
{
$this->_mapper = $mapper;
return $this;
}
/**
* Get data mapper.
*
* Lazy loads Application_Model_PostMapper instance if no mapper
* registered.
*
* #return Application_Model_PostMapper
*/
public function getMapper()
{
if (null === $this->_mapper) {
$this->setMapper(new Application_Model_PostMapper());
}
return $this->_mapper;
}
/**
* Save the current post.
*
* #return void
*/
public function save()
{
$this->getMapper()->save($this);
}
public function getPost($id)
{
return $this->getMapper()->getPost($id);
}
/**
* Update the current post.
*
* #return void
*/
public function update($data, $where)
{
$this->getMapper()->update($data, $where);
}
/**
* Find a post.
*
* Resets entry state if matching id found.
*
* #param int $id
* #return Application_Model_Post
*/
public function find($id)
{
$this->getMapper()->find($id, $this);
return $this;
}
/**
* Fetch all posts.
*
* #return array
*/
public function fetchAll()
{
return $this->getMapper()->fetchAll();
}
}
getMapper refers to the class Application_Model_PostMapper.
class Application_Model_PostMapper
{
public function save(Application_Model_Post $post)
{
$data = array(
'title'=>$post->getTitle(),
'body'=>$post->getBody(),
'created'=>$post->getCreated()
);
if (null === ($id = $post->getId())) {
unset($data['id']);
$data['created'] = date('Y-m-d H:i:s');
$post->setId($this->getDbTable()->insert($data));
} else {
$this->getDbTable()->update($data, array('id = ?'=>$id));
}
}
public function getDbTable()
{
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_Post');
}
return $this->_dbTable;
}
}
Class of Application_Model_DbTable_Post
class Application_Model_DbTable_Post extends Zend_Db_Table_Abstract
{
protected $_name = 'posts';
}
Let me know if anything is incorrect. i am a newbie to zend and did thsi while referring the zend site. http://framework.zend.com/manual/1.12/en/learning.quickstart.create-model.html
you can extend your script like this. zend dbtable triggers the Zend_Db_Exception on any error during any insert or update.
class Application_Model_PostMapper
{
public function save(Application_Model_Post $post)
{
$data = array(
'title'=>$post->getTitle(),
'body'=>$post->getBody(),
'created'=>$post->getCreated()
);
try {
if (null === ($id = $post->getId())) {
unset($data['id']);
$data['created'] = date('Y-m-d H:i:s');
$post->setId($this->getDbTable()->insert($data));
} else {
$this->getDbTable()->update($data, array('id = ?'=>$id));
}
} catch (Zend_Db_Exception $e) {
// error thrown by dbtable class
return $e->getMessage();
}
// no error
return true;
}
}
now you can check like this
$post = new Application_Model_Post($form->getValues());
$post->setId($id);
$isSaved = $post->save();
if ($isSaved === true) {
$this->_helper->flashMessenger->addMessage('Post updated');
} else {
// error
// $isSaved holds the error message
$this->_helper->flashMessenger->addMessage('Post cannot update');
}

Fatal error: Declaration of registerContainerConfiguration must be compatible with that of Kernel::registerContainerConfiguration

Do anyone know why this occurs?
as far I can get, the child class method is declared in the same way as parent's.
Thanks!
here is my kernel code:
<?php
require_once __DIR__.'/../src/autoload.php';
use Symfony\Framework\Kernel;
use Symfony\Components\DependencyInjection\Loader\YamlFileLoader as ContainerLoader;
use Symfony\Components\Routing\Loader\YamlFileLoader as RoutingLoader;
use Symfony\Framework\KernelBundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\ZendBundle\ZendBundle;
use Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle;
use Symfony\Bundle\DoctrineBundle\DoctrineBundle;
use Symfony\Bundle\DoctrineMigrationsBundle\DoctrineMigrationsBundle;
use Symfony\Bundle\DoctrineMongoDBBundle\DoctrineMongoDBBundle;
use Symfony\Bundle\PropelBundle\PropelBundle;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Application\UfaraBundle\UfaraBundle;
class UfaraKernel extends Kernel {
public function registerRootDir() {
return __DIR__;
}
public function registerBundles() {
$bundles = array(
new KernelBundle(),
new FrameworkBundle(),
new ZendBundle(),
new SwiftmailerBundle(),
new DoctrineBundle(),
//new DoctrineMigrationsBundle(),
//new DoctrineMongoDBBundle(),
//new PropelBundle(),
//new TwigBundle(),
new UfaraBundle(),
);
if ($this->isDebug()) {
}
return $bundles;
}
public function registerBundleDirs() {
$bundles = array(
'Application' => __DIR__.'/../src/Application',
'Bundle' => __DIR__.'/../src/Bundle',
'Symfony\\Framework' => __DIR__.'/../src/vendor/symfony/src/Symfony/Framework',
'Symfony\\Bundle' => __DIR__.'/../src/vendor/symfony/src/Symfony/Bundle',
);
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader) {
return $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
public function registerRoutes() {
$loader = new RoutingLoader($this->getBundleDirs());
return $loader->load(__DIR__.'/config/routing.yml');
}
}
here is the parent class code:
<?php
namespace Symfony\Framework;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
use Symfony\Component\DependencyInjection\Resource\FileResource;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Loader\DelegatingLoader;
use Symfony\Component\DependencyInjection\Loader\LoaderResolver;
use Symfony\Component\DependencyInjection\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Framework\ClassCollectionLoader;
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier#symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* The Kernel is the heart of the Symfony system. It manages an environment
* that can host bundles.
*
* #author Fabien Potencier <fabien.potencier#symfony-project.org>
*/
abstract class Kernel implements HttpKernelInterface, \Serializable
{
protected $bundles;
protected $bundleDirs;
protected $container;
protected $rootDir;
protected $environment;
protected $debug;
protected $booted;
protected $name;
protected $startTime;
protected $request;
const VERSION = '2.0.0-DEV';
/**
* Constructor.
*
* #param string $environment The environment
* #param Boolean $debug Whether to enable debugging or not
*/
public function __construct($environment, $debug)
{
$this->environment = $environment;
$this->debug = (Boolean) $debug;
$this->booted = false;
$this->rootDir = realpath($this->registerRootDir());
$this->name = basename($this->rootDir);
if ($this->debug) {
ini_set('display_errors', 1);
error_reporting(-1);
$this->startTime = microtime(true);
} else {
ini_set('display_errors', 0);
}
}
public function __clone()
{
if ($this->debug) {
$this->startTime = microtime(true);
}
$this->booted = false;
$this->container = null;
$this->request = null;
}
abstract public function registerRootDir();
abstract public function registerBundles();
abstract public function registerBundleDirs();
abstract public function registerContainerConfiguration(LoaderInterface $loader);
/**
* Checks whether the current kernel has been booted or not.
*
* #return boolean $booted
*/
public function isBooted()
{
return $this->booted;
}
/**
* Boots the current kernel.
*
* This method boots the bundles, which MUST set
* the DI container.
*
* #throws \LogicException When the Kernel is already booted
*/
public function boot()
{
if (true === $this->booted) {
throw new \LogicException('The kernel is already booted.');
}
if (!$this->isDebug()) {
require_once __DIR__.'/bootstrap.php';
}
$this->bundles = $this->registerBundles();
$this->bundleDirs = $this->registerBundleDirs();
$this->container = $this->initializeContainer();
// load core classes
ClassCollectionLoader::load(
$this->container->getParameter('kernel.compiled_classes'),
$this->container->getParameter('kernel.cache_dir'),
'classes',
$this->container->getParameter('kernel.debug'),
true
);
foreach ($this->bundles as $bundle) {
$bundle->setContainer($this->container);
$bundle->boot();
}
$this->booted = true;
}
/**
* Shutdowns the kernel.
*
* This method is mainly useful when doing functional testing.
*/
public function shutdown()
{
$this->booted = false;
foreach ($this->bundles as $bundle) {
$bundle->shutdown();
$bundle->setContainer(null);
}
$this->container = null;
}
/**
* Reboots the kernel.
*
* This method is mainly useful when doing functional testing.
*
* It is a shortcut for the call to shutdown() and boot().
*/
public function reboot()
{
$this->shutdown();
$this->boot();
}
/**
* Gets the Request instance associated with the master request.
*
* #return Request A Request instance
*/
public function getRequest()
{
return $this->request;
}
/**
* Handles a request to convert it to a response by calling the HttpKernel service.
*
* #param Request $request A Request instance
* #param integer $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
* #param Boolean $raw Whether to catch exceptions or not
*
* #return Response $response A Response instance
*/
public function handle(Request $request = null, $type = HttpKernelInterface::MASTER_REQUEST, $raw = false)
{
if (false === $this->booted) {
$this->boot();
}
if (null === $request) {
$request = $this->container->get('request');
} else {
$this->container->set('request', $request);
}
if (HttpKernelInterface::MASTER_REQUEST === $type) {
$this->request = $request;
}
$response = $this->container->getHttpKernelService()->handle($request, $type, $raw);
$this->container->set('request', $this->request);
return $response;
}
/**
* Gets the directories where bundles can be stored.
*
* #return array An array of directories where bundles can be stored
*/
public function getBundleDirs()
{
return $this->bundleDirs;
}
/**
* Gets the registered bundle names.
*
* #return array An array of registered bundle names
*/
public function getBundles()
{
return $this->bundles;
}
/**
* Checks if a given class name belongs to an active bundle.
*
* #param string $class A class name
*
* #return Boolean true if the class belongs to an active bundle, false otherwise
*/
public function isClassInActiveBundle($class)
{
foreach ($this->bundles as $bundle) {
$bundleClass = get_class($bundle);
if (0 === strpos($class, substr($bundleClass, 0, strrpos($bundleClass, '\\')))) {
return true;
}
}
return false;
}
/**
* Returns the Bundle name for a given class.
*
* #param string $class A class name
*
* #return string The Bundle name or null if the class does not belongs to a bundle
*/
public function getBundleForClass($class)
{
$namespace = substr($class, 0, strrpos($class, '\\'));
foreach (array_keys($this->getBundleDirs()) as $prefix) {
if (0 === $pos = strpos($namespace, $prefix)) {
return substr($namespace, strlen($prefix) + 1, strpos($class, 'Bundle\\') + 7);
}
}
}
public function getName()
{
return $this->name;
}
public function getSafeName()
{
return preg_replace('/[^a-zA-Z0-9_]+/', '', $this->name);
}
public function getEnvironment()
{
return $this->environment;
}
public function isDebug()
{
return $this->debug;
}
public function getRootDir()
{
return $this->rootDir;
}
public function getContainer()
{
return $this->container;
}
public function getStartTime()
{
return $this->debug ? $this->startTime : -INF;
}
public function getCacheDir()
{
return $this->rootDir.'/cache/'.$this->environment;
}
public function getLogDir()
{
return $this->rootDir.'/logs';
}
protected function initializeContainer()
{
$class = $this->getSafeName().ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
$location = $this->getCacheDir().'/'.$class;
$reload = $this->debug ? $this->needsReload($class, $location) : false;
if ($reload || !file_exists($location.'.php')) {
$this->buildContainer($class, $location.'.php');
}
require_once $location.'.php';
$container = new $class();
$container->set('kernel', $this);
return $container;
}
public function getKernelParameters()
{
$bundles = array();
foreach ($this->bundles as $bundle) {
$bundles[] = get_class($bundle);
}
return array_merge(
array(
'kernel.root_dir' => $this->rootDir,
'kernel.environment' => $this->environment,
'kernel.debug' => $this->debug,
'kernel.name' => $this->name,
'kernel.cache_dir' => $this->getCacheDir(),
'kernel.logs_dir' => $this->getLogDir(),
'kernel.bundle_dirs' => $this->bundleDirs,
'kernel.bundles' => $bundles,
'kernel.charset' => 'UTF-8',
'kernel.compiled_classes' => array(),
),
$this->getEnvParameters()
);
}
protected function getEnvParameters()
{
$parameters = array();
foreach ($_SERVER as $key => $value) {
if ('SYMFONY__' === substr($key, 0, 9)) {
$parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
}
}
return $parameters;
}
protected function needsReload($class, $location)
{
if (!file_exists($location.'.meta') || !file_exists($location.'.php')) {
return true;
}
$meta = unserialize(file_get_contents($location.'.meta'));
$time = filemtime($location.'.php');
foreach ($meta as $resource) {
if (!$resource->isUptodate($time)) {
return true;
}
}
return false;
}
protected function buildContainer($class, $file)
{
$parameterBag = new ParameterBag($this->getKernelParameters());
$container = new ContainerBuilder($parameterBag);
foreach ($this->bundles as $bundle) {
$bundle->registerExtensions($container);
if ($this->debug) {
$container->addObjectResource($bundle);
}
}
if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
$container->merge($cont);
}
$container->freeze();
foreach (array('cache', 'logs') as $name) {
$dir = $container->getParameter(sprintf('kernel.%s_dir', $name));
if (!is_dir($dir)) {
if (false === #mkdir($dir, 0777, true)) {
die(sprintf('Unable to create the %s directory (%s)', $name, dirname($dir)));
}
} elseif (!is_writable($dir)) {
die(sprintf('Unable to write in the %s directory (%s)', $name, $dir));
}
}
// cache the container
$dumper = new PhpDumper($container);
$content = $dumper->dump(array('class' => $class));
if (!$this->debug) {
$content = self::stripComments($content);
}
$this->writeCacheFile($file, $content);
if ($this->debug) {
$container->addObjectResource($this);
// save the resources
$this->writeCacheFile($this->getCacheDir().'/'.$class.'.meta', serialize($container->getResources()));
}
}
protected function getContainerLoader(ContainerInterface $container)
{
$resolver = new LoaderResolver(array(
new XmlFileLoader($container, $this->getBundleDirs()),
new YamlFileLoader($container, $this->getBundleDirs()),
new IniFileLoader($container, $this->getBundleDirs()),
new PhpFileLoader($container, $this->getBundleDirs()),
new ClosureLoader($container),
));
return new DelegatingLoader($resolver);
}
/**
* Removes comments from a PHP source string.
*
* We don't use the PHP php_strip_whitespace() function
* as we want the content to be readable and well-formatted.
*
* #param string $source A PHP string
*
* #return string The PHP string with the comments removed
*/
static public function stripComments($source)
{
if (!function_exists('token_get_all')) {
return $source;
}
$output = '';
foreach (token_get_all($source) as $token) {
if (is_string($token)) {
$output .= $token;
} elseif (!in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
$output .= $token[1];
}
}
// replace multiple new lines with a single newline
$output = preg_replace(array('/\s+$/Sm', '/\n+/S'), "\n", $output);
// reformat {} "a la python"
$output = preg_replace(array('/\n\s*\{/', '/\n\s*\}/'), array(' {', ' }'), $output);
return $output;
}
protected function writeCacheFile($file, $content)
{
$tmpFile = tempnam(dirname($file), basename($file));
if (false !== #file_put_contents($tmpFile, $content) && #rename($tmpFile, $file)) {
chmod($file, 0644);
return;
}
throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file));
}
public function serialize()
{
return serialize(array($this->environment, $this->debug));
}
public function unserialize($data)
{
list($environment, $debug) = unserialize($data);
$this->__construct($environment, $debug);
}
}
Your answer lies in the imported namespaces. In the Kernel's file, there's this use clause:
use Symfony\Component\DependencyInjection\Loader\LoaderInterface;
So that ties LoaderInterface to the fully namespaced class Symfony\Component\DependencyInjection\Loader\LoaderInterface.
Basically making the signature:
public function registerContainerConfiguration(Symfony\Component\DependencyInjection\Loader\LoaderInterface $loader);
In your class, you don't import that namespace. So PHP by default assumes the class is in your namespace (since none of the imported namespaces have that interface name).
So your signature is (since you don't declare a namespace):
public function registerContainerConfiguration(\LoaderInterface $loader);
So to get them to match, simply add the use line to the top of your file:
use Symfony\Component\DependencyInjection\Loader\LoaderInterface;

Categories