How to receive a variable in method automatically? - variables

Is it possible to define a method like below to receive $id?
public function action_delete($id){
}
I've defined a route
Route::set('tweet', 'tweet/delete/<id>', array('id' => '\d+'))->defaults(array(
'controller'=>'tweet',
'action'=>'delete'
));
I remember a code snippet something like this few months ago...
Updated: I get the following error message
Missing argument 1 for Controller_Tweet::action_delete()

If your Kohana version < 3.2 then you can use this, however it is highly recommended that you get the id value with $this->request->param('id') -> this is the only way since 3.2 version:
public function action_delete(){
$id = $this->request->param('id');
// Rest of tour code
}

In Kohana 3.2, this doesn't work anymore. You'll have to retrieve the variable through
$id = $this->request->param('id');
See: http://kohanaframework.org/3.2/guide/api/Request#param

Related

Lumen 8 - Using Faker in tests makes InvalidArgumentException: Unknown format "name"

I'm using Lumen default Tests only added this line to the test :
$users = \App\Models\User::factory()->count(5)->create();
But i get this error when running the test :
InvalidArgumentException: Unknown format "name"
I did't touch the UserFactory Class i include it below , whats wrong with my code?
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
];
}
Should anybody else end up here looking for a similar issue in Laravel, make sure you include
parent::setUp();
in your setup method (if you have one). For example,
class ManageDocumentTest extends TestCase
{
public $user;
public function setUp():void
{
parent::setUp();
$this->user = User::factory()->create();
...
Uncommented these lines in app.php and its working now :
$app->withFacades();
$app->withEloquent();
You have to extend use Tests\TestCase instead of PHPUnit\Framework\TestCase.
At least, it helped me.
If you are using Tests\TestCase, calling parent::setUp(); and it still doesn't work, make sure not to call $faker before the actual test - ie. in a #dataProvider it won't work

Symfony 3.4 : "Could not load type ... : class does not exist"

Sorry, I'm a beginner at Symfony and I've tried to find an answer but nothing worked. I'm using Symfony3.4 which was updated from Symfony 2.8 a few months ago.
Now, I'm trying to do a rather simple thing : using a formType in a Controller, but no matter what, Symfony keeps showing the following error : Could not load type "Cha\GeneralBundle\Form\StripePaymentType": class does not exist.
Here's my StripePaymentType -really, really basic:
namespace Cha\GeneralBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
class StripePaymentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', TextType::class);
}
public function getBlockPrefix()
{
return 'cha_stripe_payment_form';
}
}
Here's my Controller action, once again, a basic thing (I didn't even write any code in there, because of this strange error) :
public function upgradeOfferPaymentAction(Offers $offers)
{
$form = $this->createForm(StripePaymentType::class);
return $this->render(
'#ChaGeneral/Offers/offer_payment.html.twig', array(
'form' => $form->createView()
));
}
I tried to use my form as a service but it did not work either :
cha.stripe.payment.form:
class: Cha\GeneralBundle\Form\StripePaymentType
tags:
- { name: cha_stripe_payment_form }
I'm probably missing something but I can't figure what...
Thank in advance for your help!
You must add this line at the top of the form class:
use Symfony\Component\Form\Extension\Core\Type\TextType;
Revert the SF version is not a solution, is just dodge the problem.
Well, finally I found what caused this problem : somebody did a composer update and we updated from Symfony 3.4.13 to Symfony 3.4.14. A simple revert did the trick, now everything is working again.
Thanks a lot for your help!

vanilla php ldap query works. Symfony 3 ldap query fails. Why?

I'm trying to figure out how to use the Ldap class in Symfony3. I've successfully created and bound a connection but I can't get any results on a query. To make sure that the query actually works, I ran a bare php version:
if($lconn = ldap_connect('ds.mydomain.ca')){
ldap_set_option($lconn, LDAP_OPT_REFERRALS, 0);
ldap_set_option($lconn, LDAP_OPT_PROTOCOL_VERSION, 3);
if($lbind = ldap_bind($lconn,'webuser','password')){
$filter ="(&(sn=Smith)(givenname=J*))";
if(!$result = ldap_search($lconn, "dc=ds, dc=mydomain, dc=ca", $filter)) throw \Exception("Error in search query: ".ldap_error($lconn));
$output = ldap_get_entries($lconn, $result);
}else{
$output='bind failed';
}
} else {
$output= 'connection failed';
}
It returns the expected number of results.
On the other hand, this query done with Symfony 3's Ldap component returns 0 results:
//use Symfony\Component\Ldap\Ldap
$ldap = Ldap::create('ext_ldap', array(
'host' => 'ds.mydomain.ca',
'version' => 3,
'debug' => true,
'referrals' => false,
));
$ldap->bind('webuser', 'password');
$q = $ldap->query("dc=ds, dc=nrc, dc=ca", "(&(sn=Smith)(givenname=J*))");
$output = $q->execute();
Any idea why the Symfony ldap query fails when all its options should be identical to those I used for the bare php query?
I reposted this question on the Symfony github. #ChadSikorra was there too. And he made it clear what my issue was. Here's his explanation:
If you look at the collection class, nothing is done with the result
resource until initialize() is called in the class. If you do
return array('output' => array('bare' => $bare, 'symfony' =>
$symf->toArray())); it will call initialize and you'll see the
entries populated in the class. Unless there's something else going
on.
Do you still experience this issue with the latest 3.1+ versions?
Sorry but I don't go very often on Stack Overflow and spend most of my time on Github so I didn't see your question before.
As #ChadSikorra said, you should be using the toArray() method of the resulting Collection class, or you should iterate on the results directly.
The implementation is made so that the results are traversed in a memory-efficient manner, without storing all the results in an array by default, but the toArray() method can do this for you. Behind the scenes,it actually converts the resulting itératif to an array using the appropriate PHP function (iterator_to_array).
By the way, there used to be some inconsistency between the iterator and the toArray() function call, but that has been fixed in recent versions.
Cheers!

Get the id I am passing YII

Im still new to yii and havent been really familar in everything so what i want to do is get the value of the id (xwrg/ixxdfgx.xxx?r=vintages/view&id=2) say my id here is 2 and echo it
Please I hope someone can help
Also, if you use named parameters in your urlManager rules (main/config.php):
'/vintages/<id:\d+>' => 'Vintages/Index', // i.e. http://example.com/vintages/15
Then you can access them like this:
public function actionIndex( $id )
{
echo $id; // Outputs 15
}

CakePHP: get user info in models

I'm moving some of my find code inside models.
Previously in my controller I had
$this->Book->Review->find('first', array(
'conditions' => array(
'Review.book_id' => $id,
'Review.user_id' => $this->Auth->user('id')
)
));
so in my Review model I put something like
function own($id) {
$this->contain();
$review = $this->find('first', array(
'conditions' => array(
'Review.book_id' => $id,
'Review.user_id' => AuthComponent::user('id')
)
));
return $review;
}
So I'm calling AuthComponent statically from the Model. I know I can do this for the method AuthComponent::password(), which is useful for validation. But I'm getting errors using the method AuthComponent::user(), in particular
Fatal error: Call to a member function
check() on a non-object in
/var/www/MathOnline/cake/libs/controller/components/auth.php
on line 663
Is there a way to get the info about the currently logged user from a model?
Create a new function in the "app_model.php" ("AppModel.php" in CakePHP 2.x), so it will be available at all models within our application:
function getCurrentUser() {
// for CakePHP 1.x:
App::import('Component','Session');
$Session = new SessionComponent();
// for CakePHP 2.x:
App::uses('CakeSession', 'Model/Datasource');
$Session = new CakeSession();
$user = $Session->read('Auth.User');
return $user;
}
in the model:
$user = $this->getCurrentUser();
$user_id = $user['id'];
$username = $user['username'];
The way that I use is this:
App::import('component', 'CakeSession');
$thisUserID = CakeSession::read('Auth.User.id');
It seems to work quite nicely :-)
I think the code is fine as it is and belongs in the Controller, or at the very least it needs to receive the ids from the Controller and not try to get them itself. The Model should only be concerned with fetching data from a data store and returning it. It must not be concerned with how the data is handled in the rest of the application or where the parameters to its request are coming from. Otherwise you paint yourself into a corner where the ReviewModel can only retrieve data for logged in users, which might not always be what you want.
As such, I'd use a function signature like this:
function findByBookAndUserId($book_id, $user_id) {
…
}
$this->Review->findByBookAndUserId($id, $this->Auth->user('id'));
There is a nice solution by Matt Curry. You store the data of the current logged user in the app_controller using the beforeFilter callback and access it later using static calls. A description can be found here:
http://www.pseudocoder.com/archives/2008/10/06/accessing-user-sessions-from-models-or-anywhere-in-cakephp-revealed/
EDIT: the above link is outdated: https://github.com/mcurry/cakephp_static_user
I think this is not good idea to get value from Session. Better solution to get logged user id inside any model simply try this:
AuthComponent::user('id');
This will work almost every where. View, Model and Controller
Dirtiest way would be to just access the user information in the Session. Least amount of overhead associated with that.
The "proper" way would probably be to instantiate the AuthComponent object, so that it does all the stuff it needs to be fully operational. Much like a death star, the AuthComponent doesn't really work well when not fully setup.
To get a new AC object, in the model:
App::import( 'Component', 'Auth' );
$this->Auth = new AuthComponent();
Now you can use $this->Auth in the model, same as you would in the controller.
For CakePHP 3.x this easy component is available: http://cakemanager.org/docs/utils/1.0/components/globalauth/. Direct accessing the Session is not possible because of different SessionKeys.
With the GlobalAuthComponent you can access your user-data everywhere with: Configure::read('GlobalAuth');.
Greetz
Bob
I use cake 2.2 and these both work great:
$this->Session->read('Auth.User');
//or
$this->Auth->user();
You can also get a field of currently logged in user:
$this->Session->read('Auth.User.email');
//or
$this->Auth->user()['email'];
None of these solutions work in CakePHP version 3. Anyone know of a way to do this? Right now, I'm completely stepping around the framework by accessing the $_SESSION variable directly from my model.