Laravel Twitter Library - Where is the static function getUserTimeline() - php

I'm new in Laravel, I'm trying to understand how it works. I have setup this library as defined.
https://github.com/thujohn/twitter-l4
Examples works perfect when I define use with only Twitter; Shown below
use Stream;
use Twitter;
class GoController extends \BaseController{
function go($id){
return Twitter::getUserTimeline(array('screen_name' => 'thujohn', 'count' => 20, 'format' => 'json'));
}
}
but it throws this error when I use Thujohn\Twitter\Twitter;
use Stream;
use Thujohn\Twitter\Twitter;
class GoController extends \BaseController{
function go($id){
return Twitter::getUserTimeline(array('screen_name' => 'thujohn', 'count' => 20, 'format' => 'json'));
}
}
Non-static method Thujohn\Twitter\Twitter::getUserTimeline() should
not be called statically, assuming $this from incompatible context
So, I'm unable to understand why I can't use the second form?

Beacuse in the second example you're using the class directly, which happens to have the same name as the alias accessor.
What you see called statically is a Façade, which actually instantiates the class by using a static method (I'm not really good at explaining things...)
If you followed the instructions you should have created an Alias in the config/app.php file.
'Twitter' => 'Thujohn\Twitter\TwitterFacade',
And this alias is the very Twitter class (i.e., the façade) you need to call, and that you see called in the documentation.
So, remove the use statement use Thujohn\Twitter\Twitter; and your code will be using the "Twitter" alias (like it did in the first example), i.e. will call the Facade accessor.
use Stream;
class GoController extends \BaseController
{
public function go($id)
{
return \Twitter::getUserTimeline(array('screen_name' => 'thujohn', 'count' => 20, 'format' => 'json'));
}
}

Related

Laravel 5 Constant define

I tried all the options. Still, it is showing "Constant expression contains invalid operations". I am using Laravel 5.5, Please Help. I need to define table name in constant and use it in Model.
I wrote in Model:
protected $table = Config::get('constants.dbTable.EMAILTEMPLATE');
And In constant.php inside Config:
return [ 'langs' =>
[
'es' => 'www.domain.es',
'en' => 'www.domain.us' // etc
],
'siteTitle' => 'HD Site',
'pagination' => 5,
'tagLine' => 'Do the best',
'dbTable'=>[
'EMAILTEMPLATE' => 'stmd_emailTemplate'
]
];
I want to use emailTemplate table.
Based on the code you have posted in the comment, you are trying to assign a value into a property in your model but you are assigning it too early (assumed from the keyword protected.) You can't do this:
class SomeModel extends Model
{
protected $someProperty = config('some.value'); // Too early!
}
because you are trying to initialize a property that requires a run-time interpretation.
There's a workaround; use your constructor.
class SomeModel extends Model
{
protected $someProperty; // Define only...
public function __construct() {
parent::__construct(); // Don't forget this, you'll never know what's being done in the constructor of the parent class you extended
$this->someProperty = config('some.value');
}
}

Codeception\Util\Stub methods ::exactly and ::once don't work

I am using Codeception\Util\Stub to create unit tests. And I want to be sure that my method called several times. For this I am using method 'exactly'.
Example:
use \UnitTester;
use \Codeception\Util\Stub as StubUtil;
class someCest
{
public function testMyTest(UnitTester $I)
{
$stub = StubUtil::makeEmpty('myClass', [
'myMethod' => StubUtil::exactly(2, function () { return 'returnValue'; })
]);
$stub->myMethod();
}
}
As you can see I called myMethod once. But test passed.
The same problem with method ::once , because this method is using the same class PHPUnit_Framework_MockObject_Matcher_InvokedCount ('matcher' below).
Test will fail only if I will call more then expected times ( >2 ). Because matcher's method 'invoked' checks if count more then expected. But can't see if someone call matcher's method 'verify' to check if myMethod called less then expected.
Sorry stackoverflow, this is my first question.
UPDATE
My fast and BAD temporary solution:
Add stub into helper
$I->addStubToVerify($stub);
Add method into helper to validate:
protected $stubsToVerify = [];
public function verifyStubs()
{
foreach ($this->stubsToVerify as $stub) {
$stub->__phpunit_getInvocationMocker()->verify();
}
return $this;
}
Call this method in Cest's method _after():
public function _after(UnitTester $I)
{
$I->verifyStubs();
}
You need to pass $this as a third parameter to makeEmpty:
$stub = StubUtil::makeEmpty('myClass', [
'myMethod' => StubUtil::exactly(2, function () { return 'returnValue'; })
], $this);
Instead of use \Codeception\Util\Stub to Expected::once(), modify your unit tests to extends \Codeception\Test\Unit then use $this->make() or $this->makeEmpty() to create your stubs. It will works as you expect ;)
For example:
class MyProcessorTest extends \Codeception\Test\Unit
{
public function testSomething()
{
$processor = new MyProcessor(
$this->makeEmpty(EntityManagerInterface::class, [
'remove' => Expected::never(),
'persist' => Expected::once(),
'flush' => Expected::once(),
])
);
$something = $this->somethingFactory(Processor::OPERATION_CREATE);
$processor->process($something);
}
}
Cheers!
Looks like your method does not exist in the target class that you mock.
If the method exists then Codeception replaces it with the stub you provide. And if this method does not exist then Codeception adds a field with this name to the stub object.
It is because methods and properties are passed in the same array so Codeception has no other way to tell methods from properties.
So first create a method myMethod in your class myClass.

Laravel 4 - Access Auth Class in Validation Class

I want to access the Auth Class within my ValidatorService Class.
namespace Services\Validators\User;
use \Services\Validators\Validator;
use \Illuminate\Support\Facades\Auth;
class Edit extends Validator {
public static $rules = [
'email' => 'required|unique:users,email,'.Auth::user()->id
];
}
I tried to use the \Illuminate\Support\Facades\Auth Namespace, but laravel throws an Exception.
Error: syntax error, unexpected '.', expecting ']'
Laravel only throws the exception, when I try to use Auth::user()->id.
If I remove Auth::user()->id and add a number, for example 1, it works.
I also tried to implement the Illuminate\Auth\UserInterface but it is not working.
How can I use the Auth Class in my ValidatorService Class?
EDIT: Problem solved -> Scroll down.
Solution:
You cannot use functions or variables when setting a variable on a
class.
Thanks to AndreasLutro on http://laravel.io/irc
So I removed the class variable and added a method.
Now everythings works fine.
Code:
class Edit extends Validator{
public static function rules(){
return array(
'email' => 'required|unique:users,email,'.Auth::user()->id
);
}
}
Cheers, Steven.
Try to surround the 'required|unique:users,email,'.Auth::user()->id
part with ( and ) so that it looks like this:
public static $rules = [
'email' => ('required|unique:users,email,' . Auth::user()->id)
];

How do I use the params/get the controller for a hook in CodeIgniter?

I have a post-controller hook:
$hook['post_controller'][] = array(
'class' => 'PostControllerHook',
'function' => 'post_controller',
'filename' => 'PostControllerHook.php',
'filepath' => 'hooks',
'params' => array('controller')
);
The hooks documentation says that I can specify paramaters for my hook. How do I specify these parameters? Also, I need to have access to my controller object, which is why I'm trying to pass it as a parameter.
You are passing the parameters correctly.
Are you expecting to have access to the controller that just ran, prior to the post_controller hook? That won't work quite the way you expect. Code Igniter will try to instantiate a class if you pass it one for the hook, so you can't pass the controller instance directly.
Imagine first you have a controller
class Blog extends CI_Controller
{
public function doHookStuff()
{
echo "I'm running in a hook I hope!";
}
}
What you can do is call the get_instance helper function from your hook.
class PostControllerHook
{
function post_controller($params)
{
// $params[0] = 'controller' (given the params in the question)
// $controller is now your controller instance,
// the same instance that just handled the request
$controller =& get_instance();
$controller->doHookStuff();
}
}
If you want more info, all the answers are sitting in system/core/CodeIgniter.php and system/core/Hooks.php. A little complicated, but not too bad.

ZendFramework 2.0.0beta4 Service Manager Configuration - Difference between sub-keys

EDIT: a few weeks after I posted this question Evan Coury wrote an excellent blog post on the topic of the ZF2 ServiceManager, which is where I found the best answers to my questions: http://blog.evan.pro/introduction-to-the-zend-framework-2-servicemanager
--
I'm working on a project using ZendFramework 2.0.0beta4 and am having trouble using the Zend\ServiceManager to handle dependencies. Here is the current ZF2 ServiceManager documentation
It lists 6 sub-keys to use when registering classes with the ServiceManager for use in our modules: abstract_factories, aliases, factories, invokables, services, and shared. If I just want to register a model class which I'm going to use in my controller to pull data from a database, which one is best? I'm specifically trying to adapt an example from the ZF2 Skeleton Application shown below to my own application (DashboardTable is a model), and this example uses the factories way.
public function getServiceConfiguration()
{
return array(
'factories' => array(
'album-table' => function($sm) {
$dbAdapter = $sm->get('db-adapter');
$table = new DashboardTable($dbAdapter);
return $table;
},
'test-model' => Dashboard\Model\TestModel(),
),
);
}
However, I don't know how 'db-adapter' is getting into the ServiceManager ($sm) in my separate working example from the SkeletonApplication - it has to do with an entry in the autoloaded global.php config file which has a 'db' entry containing the DB info. Because I don't know exactly how that's getting from the config file to ServiceManager, I created the simple entry below that to reduce the problem to its base components - "test-model". When I comment out the 'dashboard-table' entry and call a function from TestModel in my controller which simply outputs some text. Below is the ServiceManager config from my Module.php
<?php
namespace Dashboard\Model;
class TestModel {
public function testMethod()
{
$testResult = "Hello";
return $testResult;
}
}
Which is then passed from my controller to the view:
<?php
namespace Dashboard\Controller;
use Zend\Mvc\Controller\ActionController;
use Zend\View\Model\ViewModel;
use Dashboard\Model\AlbumTable;
use Dashboard\Model\TestModel;
use Dashboard\Model\Dashboard;
class DashboardController extends ActionController
{
public function indexAction()
{
return new ViewModel(array(
'users' => $this->getTestModel()->testMethod(),
));
}
public function getAlbumTable()
{
if (!$this->albumTable) {
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('album-table');
}
return $this->albumTable;
}
public function getTestModel()
{
if (!$this->testModel) {
$sm = $this->getServiceLocator();
$this->testModel = $sm->get('test-model');
}
return $this->testModel;
}
}
This code gives me a completely blank page, no errors. When I comment out the ServiceManager config from Module.php and just render a new ViewModel without any passing any arguments in my DashboardController.php file the page renders normally - loading layout.phtml and index.phtml.
I believe I'm misunderstanding a fundamental piece of how to use the ServiceManager or possible ZF2 in general, and will greatly appreciate any insight anybody can give. This is also my first question on StackOverflow so I welcome any advice on formatting my question. Thanks.
There are two good options to get factories from service managers. One is the creation of factory classes, which happens most time in the Zend Framework code itself. The second one is using closures, as you are doing.
Make sure you do not type things like:
'test-model' => Dashboard\Model\TestModel(),
But a real closure like your first one is a good example. Secondly, the Service Manager always gives an exception when you try to get a service which fails to instantiate. Note this exception does not include the message why: the class might not be found or an exception is thrown during instantiation (for example because the service manager cannot instantiate a dependency of the service you are trying to get).
A last remark is you do not need to import FQCN (fully qualified class names) with use statements at the location you are trying to get. But you need to import the FQCNs when you are trying to instantiate.
So this works:
<?php
class MyClass
{
protected $sm;
public function setServiceManager($sm)
{
$this->sm = $sm;
}
public function doSomething()
{
$this->sm->get('some-special-key');
}
}
And this too:
<?php
use Foo\Bar\Baz;
$serviceConfig = array(
'factories' => array(
'some-special-key' => function($sm) {
return new Baz;
}
),
);
But this not (if you try to get a Foo\Bar\Baz):
<?php
$serviceConfig = array(
'factories' => array(
'some-special-key' => function($sm) {
return new Baz;
}
),
);
You might want to checkout my SlmCmfKernel repository. In my Module.php I include a service configuration file, which is put in a separate location. In another part of the code I get a service from the manager.
Just to clarify:
public function getServiceConfiguration()
{
return array(
'factories' => array(
'test-model' => function($sm){
return new Model\TestModel;
},
),
);
}
Can also be written as an invokable:
public function getServiceConfiguration()
{
return array(
'invokables' => array(
'test-model' => 'Model\TestModel',
),
);
}
In that case, you might want to consider having it defined in a config file instead of Module.php, as you'd be able to take advantage of config caching since it's simply an array of scalars.
I ended up finding the answer to my own question through more debugging (I previously hadn't had ini_set('display_errors', '1'); set - silly me).
The proper syntax to add a class to the ZF2 ServiceManager (within your Module.php) appears to be:
public function getServiceConfiguration()
{
return array(
'factories' => array(
'album-table' => function($sm) {
$dbAdapter = $sm->get('db-adapter');
$table = new AlbumTable($dbAdapter);
return $table;
},
'test-model' => function($sm){
return new Model\TestModel;
},
),
);
}
And just for completeness, in order to call a method from the class you're including you can use this in your controller file (DashboardController.php in my case) as long as you're extending the ActionController class:
class DashboardController extends ActionController
{
public function indexAction()
{
return new ViewModel(array(
'users' => $this->getTestModel()->testMethod(),
));
}
public function getTestModel()
{
if (!$this->testModel) {
$sm = $this->getServiceLocator();
$this->testModel = $sm->get('test-model');
}
return $this->testModel;
}
}
Where testMethod() is a method from within the TestModel class. Some notes from this for anybody new to Zend or namespaces - one of my issues was that I was using the full class name reference (Dashboard\Model\TestModel) when I had set the namespace at the top of the file to Dashboard, so the first Dashboard was unnecessary and caused PHP to look for Dashboard\Dashboard\Model\TestModel. Also, as of this writing sample ZF2 module are scarce - I recommend looking to samples like ZfcUser by EvanDotPro for examples on this type of thing.
My original confusion about the various sub-keys for adding classes to the ServiceManager still lingers though, so if you have any insight as to that I will continue to monitor this question and will mark your answer as "the" answer should you solve that bit, thank you :).

Categories