With Google API PHP client library I use the following code, which works well and prints lot of information about the user, who authorizes my application via OAuth2:
<?php
require_once('google-api-php-client-1.1.7/src/Google/autoload.php');
const TITLE = 'My amazing app';
const REDIRECT = 'https://example.com/myapp/';
session_start();
$client = new Google_Client();
$client->setApplicationName(TITLE);
$client->setClientId('REPLACE_ME.apps.googleusercontent.com');
$client->setClientSecret('REPLACE_ME');
$client->setRedirectUri(REDIRECT);
$client->setScopes(array(Google_Service_Plus::PLUS_ME));
$plus = new Google_Service_Plus($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
error_log('The session state did not match.');
exit(1);
}
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . REDIRECT);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken() && !$client->isAccessTokenExpired()) {
try {
$me = $plus->people->get('me'); # HOW TO SPECIFY FIELDS?
$body = '<PRE>' . print_r($me, TRUE) . '</PRE>';
} catch (Google_Exception $e) {
error_log($e);
$body = htmlspecialchars($e->getMessage());
}
# the access token may have been updated lazily
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$body = sprintf('<P>Login</P>',
$client->createAuthUrl());
}
?>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE><?= TITLE ?></TITLE>
</HEAD>
<BODY>
<?= $body ?>
<P>Logout</P>
</BODY>
</HTML>
However I need less info than returned by the above script.
When entering just the fields I am interested in at the People: get "API explorer":
id,gender,name,image,placesLived
this again works well and prints only the specified fields:
MY QUESTION:
How to specify the fields in the above $me = $plus->people->get('me'); call?
After studying 1.1.7/src/Google/Service/Plus.php with the code:
/**
* Get a person's profile. If your app uses scope
* https://www.googleapis.com/auth/plus.login, this method is
* guaranteed to return ageRange and language. (people.get)
*
* #param string $userId The ID of the person to get the profile for. The
* special value "me" can be used to indicate the authenticated user.
* #param array $optParams Optional parameters.
* #return Google_Service_Plus_Person
*/
public function get($userId, $optParams = array())
{
$params = array('userId' => $userId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Plus_Person");
}
I have tried the following PHP code:
const FIELDS = 'id,gender,name,image,placesLived';
$me = $plus->people->get('me', array('fields' => urlencode(FIELDS)));
but for some reason it prints a lot of :protected strings:
Google_Service_Plus_Person Object
(
[collection_key:protected] => urls
[internal_gapi_mappings:protected] => Array
(
)
[aboutMe] =>
[ageRangeType:protected] => Google_Service_Plus_PersonAgeRange
[ageRangeDataType:protected] =>
[birthday] =>
[braggingRights] =>
[circledByCount] =>
[coverType:protected] => Google_Service_Plus_PersonCover
[coverDataType:protected] =>
[currentLocation] =>
[displayName] =>
[domain] =>
[emailsType:protected] => Google_Service_Plus_PersonEmails
[emailsDataType:protected] => array
[etag] =>
[gender] => male
...
Also I have tried just appending the fields after me:
$me = $plus->people->get('me?fields=' . urlencode(FIELDS)));
but get the 404 error:
Error calling GET
https://www.googleapis.com/plus/v1/people/me%3Ffields%3Did%252Cgender%252Cname%252Cimage%252CplacesLived:
(404) Not Found
UPDATE: I have created Issue #948 at GitHUb.
To specify which fields to get from the G+ API, you just have to specify a fields member in the options array. So actually you got very close to the solution:
$me = $plus->people->get('me', array('fields' => 'id,gender,name,image,placesLived'));
You don't even have to urlencode, as it is a default safety feature of the library itself.
The thing that might have tricked you is, that the Google_Service_Plus_Person class contains all the possible fields a protected members, not regarding the actual fields that were sent by the API. Not included fields will be empty in the object. As always, protected members should not be used in any way by the user of the class.
You, as the user of the library should only use public members, such as $me->getPlacesLived() and $me->getId(). Dumping whole objects is a nice tool during development, but in production calling the public interface is the way to go.
Related
The problem is when I entered a new name no data is added. A similar thing happen when I entered an already existing name. Still, no data is added to the database. I am still new to CodeIgniter and not entirely sure my query builder inside the model is correct or not.
In the Model, I check if the name already exists insert data only into the phone_info table. IF name does not exist I insert data into user_info and phone_info.
Controller:
public function addData()
{
$name = $this->input->post('name');
$contact_num = $this->input->post('contact_num');
if($name == '') {
$result['message'] = "Please enter contact name";
} elseif($contact_num == '') {
$result['message'] = "Please enter contact number";
} else {
$result['message'] = "";
$data = array(
'name' => $name,
'contact_num' => $contact_num
);
$this->m->addData($data);
}
echo json_encode($result);
}
Model:
public function addData($data)
{
if(mysqli_num_rows($data['name']) > 0) {
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info',$phone_info);
} else {
$user_info = array(
'name' => $data['name']
);
$this->db->insert('user_info', $user_info);
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info', $phone_info);
}
}
DB-Table user_info:
DB-Table phone_info:
Extend and change your model to this:
public function findByTitle($name)
{
$this->db->where('name', $name);
return $this->result();
}
public function addData($data)
{
if(count($this->findByTitle($data['name'])) > 0) {
//.. your code
} else {
//.. your code
}
}
Explanation:
This:
if(mysqli_num_rows($data['name']) > 0)
..is not working to find database entries by name. To do this you can use codeigniters built in model functions and benefit from the MVC Pattern features, that CodeIgniter comes with.
I wrapped the actual findByName in a function so you can adapt this to other logic and use it elswehere later on. This function uses the query() method.
Read more about CodeIgniters Model Queries in the documentation.
Sidenote: mysqli_num_rows is used to iterate find results recieved by mysqli_query. This is very basic sql querying and you do not need that in a MVC-Framework like CodeIgniter. If you every appear to need write a manual sql-query, even then you should use CodeIgniters RawQuery methods.
I need to modify the welcome email sent to user upon new account creation. I need to do this in my custom module. I tried to override the function sendNewAccountEmail in Magento\Customer\Model\Customer using preference method and also using plugin method. Both were not working.
For preference method I added the following
In Vendor/Module/etc/di.xml
<preference for="Magento\Customer\Model\Customer" type = "Vendor\Module\Model\Customer" />
Added Customer.php file in the location Vendor\Module\Model\Customer and added the following code
public function sendNewAccountEmail($type = 'registered', $backUrl = '', $storeId = '0')
{
echo "It's Working";exit;
$types = $this->getTemplateTypes();
if (!isset($types[$type])) {
throw new \Magento\Framework\Exception\LocalizedException(
__('Please correct the transactional account email type.')
);
}
if (!$storeId) {
$storeId = $this->_getWebsiteStoreId($this->getSendemailStoreId());
}
$this->_sendEmailTemplate(
$types[$type],
'customname/email/account_email_template',
['customer' => $this, 'back_url' => $backUrl, 'store' => $this->getStore()],
$storeId
);
return $this;
}
Still it's not taking the Customer.php file in the module.
echo "It's Working"; is not displaying.
What is the correct method to follow? I tried the plugin method also. It's also not working.
Looking to add tags to my mailing list members via the api. But I don't see where to pass in tags in the documentation. Can someone point to an example of how to update the tags associated with a member via the api?
If you want to create a member AND add a tag while doing so you may specify the tag attribute the following way:
$data = array(
'apikey' => $api_key,
'email_address' => $email,
'status' => $status,
'tags' => array('your-tag-name'),
'merge_fields' => array(
'FNAME' => $fname,
'LNAME' => $lname
)
);
Even though MC API some places will tell you to fill out both a name and a status, it helped me to define tags as an array but ONLY pasting in the name of the tag.
Seefan's answer in this thread helped me out and I figured i wanted to help a person who spend days (like me) to figure out how the "tags" is specified: add tags to mailchimp subscriber created via api php
Tags replaced static segments. So, the endpoints used to create tags and add and remove tags from members are the same endpoints that were previously used to manage segments. Here is the documentation on the endpoints to use to manage your tags via the API that includes the request and response body parameters as well as example requests and responses:
http://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/
In order to add tags to your members, you need to include their email addresses in the 'static_segment' array parameter.
I hope that helps.
This is the official way to add tags:
https://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/tags/
It works, except that in my testing, the response message is empty, even though the tag is added.
Here's sample code in Google Apps Script:
payload = '{\
"tags": [\
{\
"name":"' + tagName + '",\
"status":"' + tagStatus + '"\
}\
]\
}'
;
params = {
"method": "POST",
"headers":MC_headers,
"payload": payload,
"muteHttpExceptions": true
};
url = MC_url + 'lists/' + MC_IDs.listId + '/members/' + sub_hash + '/tags';
response = UrlFetchApp.fetch(url, params);
Apparently Mailchimp "tags" are "segments".
I coded a couple functions that allow me to add tags by name (rather than by ID) to a member (i.e. subscriber) by email address.
/**
*
* #param string $emailAddress
* #param array $tags
* #return void
*/
public function addTagsToContact($emailAddress, $tags) {
$list_id = $this->getDefaultListId();
foreach ($tags as $tag) {
$this->addMemberToSegment($emailAddress, $list_id, $tag);
}
}
/**
* Add a tag to a subscriber (tags replaced segments https://stackoverflow.com/a/52315577/470749)
*
* #param string $emailAddress
* #param string $list_id
* #param string $segment_name
* #return array
*/
public function addMemberToSegment($emailAddress, $list_id, $segment_name) {
$api = Newsletter::getApi();
$segmentsByName = $this->getSegments($list_id);
$segment_id = $segmentsByName[$segment_name]['id'];
$response = $api->post("lists/$list_id/segments/$segment_id", [
'members_to_add' => [$emailAddress]
]); //https://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/#create-post_lists_list_id_segments_segment_id
return $response;
}
/**
*
* #param string $list_id
* #return array
*/
public function getSegments($list_id) {//https://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/#%20
$segmentsByName = [];
$api = Newsletter::getApi();
$count = 50; //default is 10
$offset = 0;
do {
$url = "lists/$list_id/segments/?" . http_build_query(['count' => $count, 'offset' => $offset]);
Log::debug($url);
$response = $api->get($url);
$total_items = $response['total_items'];
foreach ($response['segments'] as $segment) {
$segmentsByName[$segment['name']] = $segment;
}
$offset += $count;
} while (count($segmentsByName) < $total_items);
//Log::debug(json_encode($segmentsByName));
return $segmentsByName;
}
/**
*
* #return string
*/
public function getDefaultListId() {
return config('newsletter.lists.subscribers.id');
}
This relies on the https://github.com/spatie/laravel-newsletter library.
P.S. Thanks so much to #Jelan, whose answer got me on the right track!
It took me a while to also figure this one out. Their documentation isn't clear and it seems there are 2 ways to add tags, either via the tags endpoint using POST or via the update user via a PATCH. Here's an example of the POST in PHP:
function tagUser($email){
global $api_key;
global $listId;
$hashedEmail = md5(strtolower($email));
$args = array(
'method' => 'POST',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
),
'body' => json_encode(array(
'tags' => array(['name'=>'healthy','status'=>'active'])
))
);
$response = wp_remote_post( 'https://usxx.api.mailchimp.com/3.0/lists/'.$listId.'/members/'.$hashedEmail.'/tags', $args );
$body = json_decode( $response['body'] );
}
This is code for WordPress, but should help. I did get most of this from another answer but could not find it working anywhere else.
Note this only work if the subscriber already exists on the list and then you can tag or untag them.
$api_key = XXXXXXXXXXXXXXXXXXX-us20';
$email = 'tom#gmail.com';
$list_id = 'XXXXXXXX'; //This is the list /Audience id
$tag_name_text = 'XXXXX'; //This can be whatever you want it to be. Mail chimp will add it to the tags if not already on the system
//TAGS
$args = array(
'method' => 'POST',
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
),
'body' => json_encode(array(
'tags' => array(
['name' => $tag_name_text,
'status' => 'active']
)
))
);
$response = wp_remote_post( 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/'.md5(strtolower($email)).'/tags', $args );
if ($response['response']['code'] == 200 && $body->status == $status || $response['resp`enter code here`onse']['code'] == 204) {
//echo 'The you have been successfully ' . $status . '. Please check your emails';
} else {
echo '<b>' . $response['response']['code'] . $body->title . ':</b> ' . $body->detail;
}
FULL EXAMPLE USING GRAILS TO ADD LIST OF TAGS BY NAME TO A LIST OF USERS BY EMAIL
Note you may want to setup some error checking to see if the MailChimp audience member exists.
BusinessLogicController.groovy
/*
* Add list of tags by name to list of members
*/
def addTagsByNameToUser(){
List<string> tagNamesToAdd = ['foo', 'bar']
def addResult = mailChimpService.addTagsToContactsByName(["foo#example.com", "bar#example.com"], tagNamesToAdd)
}
MailChimpService.groovy
import grails.util.Holders
import groovyx.net.http.Method
class MailChimpService {
def grailsApplication
ApiConsumerService apiConsumerService
final String AUTH = Holders.config.grails.mailChimp.auth
final String BASEURL = "https://us19.api.mailchimp.com/3.0/"
final String LISTID = "abc123"
//Add list of tags by name to list of subscribers by email
def addTagsToContactsByName(List emailAddresses, List tags = []) {
tags.each { tagName ->
addMembersToSegment(emailAddresses, tagName);
}
}
//Add a tag to a subscriber by name
def addMembersToSegment(List emailAddresses, String segmentName) {
def segmentsByName = getAllSegmentsInList()
String segmentId = segmentsByName["$segmentName"] as String
return addMailChimpTagToUsers(emailAddresses, segmentId)
}
//Get information about all available segments for a specific list.
def getAllSegmentsInList(Map query = [:]) {
String path = "lists/"+LISTID+"/segments/"
Map segments = [:]
def segmentResults = apiConsumerService.getRequest(BASEURL, path, AUTH, query, Method.GET)
segmentResults.segments.each { segment ->
segments.put(segment.name, segment.id)
}
return segments
}
//Add list of tags to a list members.
def addMailChimpTagToUsers(List emailAddresses = [], String segmentId) {
String path = "lists/LISTID/segments/" + segmentId
apiConsumerService.postRequest(BASEURL, path, AUTH, ['members_to_add': emailAddresses], Method.POST)
}
}
ApiConsumerService.groovy
import grails.transaction.Transactional
import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
#Transactional
class ApiConsumerService {
//POST REQUEST
def postRequest(String baseUrl, String path, String auth, Map query = [:], Method method = Method.POST) {
try {
HTTPBuilder http = new HTTPBuilder(baseUrl)
http.headers['Authorization'] = 'Basic ' + "${auth}".getBytes('iso-8859-1').encodeBase64()
http.request(method, ContentType.JSON) { req ->
uri.path = path
if (method == Method.POST) {
body = query
} else {
uri.query = query
}
headers.'Accept' = 'application/json'
headers.'User-Agent' = "MyPetCerts/US19"
response.success = { resp, json ->
return json
}
response.failure = { resp, json ->
println "POST response status: ${resp.statusLine}"
}
}
} catch (groovyx.net.http.HttpResponseException ex) {
ex.printStackTrace()
return null
} catch (java.net.ConnectException ex) {
ex.printStackTrace()
return null
}
}
//GET Request
def getRequest(String baseUrl, String path, String auth, Map query = [:], Method method = Method.GET) {
return postRequest(baseUrl, path, auth, query, method)
}
}
sorry if this has been asked before, I looked around but haven't found this specific question on StackOverFlow.com.
I have a view called 'view-post-wall' which I'm trying to add the form that submits posts to this view called 'post' via ajax submit, though I haven't begun adding ajax yet.
My module's name is 'friendicate'
I don't understand what I'm missing here, I'm following a tutorial and have been unable to get past this issue for 2 days now.
I don't get any errors either.
Here is the module code in full
function _form_post_ajax_add() {
$form = array();
$form['title'] = array(
'#type' => 'textfield',
'#title' => 'Title of post',
);
$form['body'] = array(
'#type' => 'textarea',
'#title' => 'description',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit post',
);
return $form;
}
function post_ajax_preprocess_page(&$variables) {
//krumo($variables);
$arg = arg();
if($arg[0] == 'view-post-wall') {
$variables['page']['content']['system_main']['main']['#markup'] = drupal_render(drupal_get_form('_form_post_ajax_add'));
}
}
There are multiple ways to accomplish this, and I'll outline those methods below. Also, if nothing works from my suggestions below, it's possible that you have an invalid form function name. Im not sure if that throws off Drupal or not. The correct format for the function name should end in _form and contain the arguments $form and $form_state, like so:
_form_post_ajax_add_form($form, &$form_state) { ... }
Also, if you want to use a hook, Steff mentioned in a comment to your question that you'll need to use your module name in the function name.
friendicate_preprocess_page(&$variables) { ... }
Ok, now for a few ideas how to get the form on the page.
Block
You can create a custom block within your module, and then assign it to a region in admin/structure/blocks
<?php
/**
* Implements hook_block_info().
*/
function friendicate_block_info() {
$blocks = array();
$blocks['post_ajax'] = array(
'info' => t('Translation Set Links'),
'cache' => DRUPAL_NO_CACHE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function friendicate_block_view($delta = '') {
$block = array();
if ($delta == 'post_ajax') {
$form = drupal_get_form('_form_post_ajax_add_form');
$block['content'] = $form;
}
return $block;
}
Clear the cache and your block should appear in admin/structure/blocks
Views attachment before/after
You can add markup before and after a view using the Views hook hook_views_pre_render()
<?php
/**
* Implements hook_view_pre_render().
*/
function frendicate_views_pre_render(&$view) {
if($view->name == 'view_post_wall') { // the machine name of your view
$form = drupal_get_form('_form_post_ajax_add_form');
$view->attachment_before = render($form);
}
}
Or maybe use view post render
function friendicate_views_post_render(&$view, &$output, &$cache) {
//use the machine name of your view
if ($view->name == 'view_post_wall') {
$output .= drupal_render(drupal_get_form('_form_post_ajax_add'));
}
}
I'm trying to build some authorization into my Phalcon-based app. In my bootstrap file I instantiate my Auth class (which extends Component), and run my authorize() function. Inside that function I get the dispatcher by calling $Dispatcher = $this->di->getShared('dispatcher').
That all seems to run fine. However, when I then call $Dispatcher->getControllerName(), it returns NULL.
How do I access the controller name?
Here is my bootstrap file:
$Debug = new \Phalcon\Debug();
$Debug->listen();
#try{
# Create a Dependency Injection container
$DI = new \Phalcon\DI\FactoryDefault();
# Load config
$Config = require '../app/config/config.php';
$DI->setShared('config',$Config);
# Register an autoloader
$Loader = new \Phalcon\Loader();
$Loader->registerDirs($Config->phalcon->load_dirs->toArray());
$Loader->registerNamespaces($Config->phalcon->namespaces->toArray());
$Loader->register();
# Initialize Session
$Session = new \Phalcon\Session\Adapter\Files();
$Session->start();
$DI->setShared('session',$Session);
# Set up the View component
$DI->set('view',function() use($Config){
$View = new \Phalcon\Mvc\View();
$View->setViewsDir($Config->dir->views_dir);
$View->registerEngines(['.phtml'=> function($View,$DI) use ($Config){
$Volt = new \Phalcon\Mvc\View\Engine\Volt($View,$DI);
$Volt->setOptions([ 'compiledPath' => $Config->dir->views_compile_dir,
'compileAlways' => $Config->app->views_compile_always
]);
return $Volt;
}
]);
$View->Config = $Config;
return $View;
});
# Check authorization
$Auth = new Auth($DI);
if($Auth->authorize()){
$DI->setShared('user',$Auth->getUser());
}
else{
$DI->get('view')->render('system','notallowed');
exit();
}
# Set up connection to database
$DI->set('db',function() use($Config){
return new \Phalcon\DB\Adapter\Pdo\Mysql([ 'host' => $Config->database->host,
'dbname' => $Config->database->database,
'username' => $Config->database->username,
'password' => $Config->database->password
]);
});
# Set up base URL
$DI->set('url',function() use($Config){
$URL = new \Phalcon\Mvc\Url();
$URL->setBaseUri('/'.basename($Config->dir->app_dir_web));
return $URL;
});
# Set up message flashing to use session instead of direct
$DI->set('flash',function(){
return new \Phalcon\Flash\Session();
});
# Handle the requested URL
$App = new \Phalcon\Mvc\Application($DI);
# Echo the output
echo $App->handle()->getContent();
/*
}
catch(\Phalcon\Exception $e){
echo 'Phalcon Exception: ',$e->getMessage();
}
*/
I think that untill you call $app->handle() the dispatcher won't be properly setup.
Maybe not a direct response, but I've manage to successfully implement authorization using Vokuro app as a example: https://github.com/phalcon/vokuro.
Your bootstrap looks ok should work.
I'm using this in bootstrap file :
/**
* Handle the request
*/
$application = new \Phalcon\Mvc\Application();
$application->setDI($di);
if (!empty($_SERVER['REQUEST_URI'])) {
$uriParts = explode('?', $_SERVER['REQUEST_URI']);
$uri = $uriParts[0];
} else {
$uri = '/';
}
echo $application->handle($uri)->getContent();
As you can see there is $uri parameter passed to $application->handle() function.
Inside controllers: $this->dispatcher->getControllerName() works fine.
I am using a Router object so the following works for me before the ->handle call
/** #var $router \Phalcon\Mvc\Router */
$router = require APPLICATION_PATH.'/routes/default.php';
$router->handle($url);
$router->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI);
/** #var $matched \Phalcon\Mvc\Router\Route */
$matched = $router->getMatchedRoute();
$paths = $matched->getPaths();
echo 'controller : ',$paths['controller'],"<br />";
echo 'action : ',$paths['action'],"<br />";
This is an old thread but in case people still need it, I will show you two ways to properly handle authorization.
In both cases, you should check authorization in a "before middleware", not anywhere else.
Checking authorization directly in your front controller is a bit premature.
1. By retrieving the handler, as you asked
Here you perform authorization checks only if needed. It is a bit more code, but a bit more effective too because you don't have to even use the database if you don't need to.
$app = \Phalcon\Mvc\Micro;
$app->before(function() use ($app)
{
/**
* #var \Phalcon\Mvc\Controller $oHandler
*/
$oHandler = null;
$sAction = null;
$aHandlerArr = (array)$app->getActiveHandler();
if (!empty($aHandlerArr) && !empty($aHandlerArr[1]))
{
$oHandler = $aHandlerArr[0];
$sAction = $aHandlerArr[1];
}
if ($oHandler && $oHandler->isAuthRequired($sAction))
{
// Do auth, and send an error if failed
}
});
2. Without voodoo magic
The other way is to simply try authorization in your before middleware without checking if you need it. It is the same code as above, but without the handler retrieval.
$app = \Phalcon\Mvc\Micro;
$app->before(function() use ($app)
{
// Do auth ...
// Set member in your app, if auth succeeded.
// Then in your controller actions, simply check for the member in your app
});
XD
$this->router->getActionName()