create site map in yii2 - yii

i want create site map in yii2
I do not know what I would do.
Help me Where do I start?
this is my news model :
/**
* #inheritdoc
*/
public static function tableName()
{
return 'news';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['news_cat_id', 'user_id','time'], 'integer'],
[['news_dec'], 'string'],
[['news_title', 'logo'], 'string', 'max' => 255]
];
}
i cant work with extension because that haven't good document.

Install package composer require evert/sitemap-php
Create command Controller for console app in #app/commands/ directory.
class SitemapController extends Controller
{
public function actionIndex(){
$host = 'http://yoursitehost.com/';
$sitemap = new Sitemap($host);
$sitemap->setPath(Yii::getAlias('#webroot').DIRECTORY_SEPARATOR);
$sitemap->addItem('', '1.0', 'daily', 'Today');
$sitemap->addItem('news', '9.0', 'daily', 'Today');
foreach(News::find()->batch(50) as $news){
foreach($news as $n){
$sitemap->addItem(Url::toRoute(['news/view', 'id' => $n->id]), '8.0', 'daily', 'Today');
}
}
$sitemap->createSitemapIndex($host, 'Today');
}
}
Add your controller to console.php config file.
$config = [
...
'controllerMap' => [
'sitemap' => [
'class' => 'app\commands\SitemapController'
],
]
];
And add to top console.php Yii::setAlias('#webroot', dirname(__DIR__) . '/../web');
Run command php yii sitemap. Script generate file sitemap.xml to web directory.
Go to link - http://yourhost.com/sitemap.xml.
You can run this command php yii sitemap by cron.

Related

Laminas Config Module Routing

I have started the latest tutorial for Laminas.
The routing for a new module called Provider is not working
A 404 error occurred
Page not found.
The requested URL could not be matched by routing.
on looking at my Module.php code I see:
getConfig() is not called but
getServiceConfig() and getControllerConfig() are.
getConfig in the Application module is not called either
<?php
namespace Provider;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\ResultSet\ResultSet;
use Laminas\Db\TableGateway\TableGateway;
use Laminas\ModuleManager\Feature\AutoloaderProviderInterface;
use Laminas\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface, AutoloaderProviderInterface
{
public function getConfig()
{
die ("getConfig");
return include __DIR__ . '/../config/module.config.php';
}
public function getAutoloaderConfig()
{
//die ("getAutoloaderConfig");
//return array(
// 'Laminas\Loader\StandardAutoloader' => array(
// 'namespaces' => array(
// __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
// ),
// ),
//);
}
public function getServiceConfig()
{
//die ("getServiceConfig");
return [
'factories' => [
Model\ProviderTable::class => function($container) {
$tableGateway = $container->get(Provider\ProviderTableGateway::class);
return new Model\ProviderTable($tableGateway);
},
Model\ProviderTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Album());
return new TableGateway('provider', $dbAdapter, null, $resultSetPrototype);
},
],
];
}
public function getControllerConfig()
{
//die ("getControllerConfig");
return [
'factories' => [
Controller\ProviderController::class => function($container) {
return new Controller\ProviderController(
$container->get(Model\ProviderTable::class)
);
},
],
];
}
}
You need to enable development mode. run composer development-enable to active development mode.
Maybe the composer json is not updated (my-application/composer.json)
"autoload": {
"psr-4": {
"Application\\": "module/Application/src/",
"Provider\\": "module/Provider/src/"
}
},
Update autoload classmap:
composer dump-autoload
https://docs.laminas.dev/tutorials/getting-started/modules/#autoloading
Have you added router configuration?
In your attached code above you have the following function :
public function getConfig()
{
//die ("getConfig"); // BE SURE YOU REMOVE THIS LINE
return include __DIR__ . '/../config/module.config.php';
}
it's include file for additional settings. in this file "/../config/module.config.php" you should add your router configuration. It should look like this:
return [
//... other setting
'router' => [
'routes' => [
// Literal route named "home"
'home' => [
'type' => 'literal',
'options' => [
'route' => '/',
'defaults' => [
'controller' => 'Application\Controller\IndexController',
'action' => 'index',
],
],
],
// Literal route named "contact"
'contact' => [
'type' => 'literal',
'options' => [
'route' => 'contact',
'defaults' => [
'controller' => 'Application\Controller\ContactController',
'action' => 'form',
],
],
],
],
],
];
more reading can be found https://docs.laminas.dev/laminas-router/routing/#simple-example-with-two-literal-routes
As mentioned before any time you add a custom module you will need to add an entry for the autoloader in composer.json and run the dump-autoload. You will also need to add an entry in the root level /config/modules.config.php file. Is there currently an entry for Application? If memory serves and your working from the examples the last two should be Application, then Album. Verify those are there and that the application is in development mode. You can check the current mode with "composer development-status". Just check composer.json in the top level and look for the "scripts" entry. The key is the command to pass to composer.
Also, be mindful of using the interfaces when configuring the application in the Module class. The Module feature methods are reserved for closures as they will not be cached when you disable development mode. Instead use the corresponding service manager array keys. that can be found here:
Service manager config:
https://docs.laminas.dev/laminas-servicemanager/configuring-the-service-manager/
Corresponding module manager feature config:
https://docs.laminas.dev/laminas-modulemanager/module-manager/
I suppose its worth mentioning that most if not all of the Feature interface methods map directly to a default pluginmanager implementation, ergo a specialized service manager.

Trying to get Laravel Dusk to behave with sqlite database

I'm trying to get Laravel Dusk to play nicely with an App i'm trying to test.
At the moment I can write to a test sqlite database but when I try to test a login form following the guidance it appears the details in the development database are being used instead.
Here's my test:
class LoginTest extends DuskTestCase
{
private $user;
use DatabaseMigrations;
public function setUp()
{
parent::setUp();
$this->user = factory(User::class)->create(['password' => bcrypt('secret')]);
}
/**
* A Dusk test example.
*
* #return void
* #throws \Exception
* #throws \Throwable
*/
public function test_user_can_log_in()
{
$this->browse(function (Browser $browser) {
$browser->visit('/login')
->assertSee('Members sign in')
->type('email', $this->user->email)
->type('password', 'secret')
->driver->executeScript('window.scrollTo(0, 500);');
$browser->press('Sign in')
->assertPathIs('/home');
});
}
}
This test fails authentication as the user I've just created doesn't exist in the development Mysql database it is reading from.
I am able to see the user I've just created in the sqlite database and can query that user exists
What am I doing wrong? Does Laravel Auth do something to override the connections?
Thank you
edit
Here is my .env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=backend_cms
DB_USERNAME=homestead
DB_PASSWORD=secret
DB_DATABASE_2=members
DB_USERNAME_2=homestead
DB_PASSWORD_2=secret
and my .env.dusk.local (I've also tried renaming to just .env.dusk but no change.
DB_CONNECTION=sqlite_testing
DUSK=true
I read that only the items you need changing should be there so assumed only the connection required?
edit
Here's the config entries in database.php
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
'sqlite_testing_memory' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
'sqlite_testing' => [
'driver' => 'sqlite',
'database' => database_path('database.sqlite'),
'prefix' => '',
],

How to login user using rest api in yii2

I new in yii2, I want login user using rest api but unable to do this.I have setup basic REST API From This blog:
budiirawan.com/setup-restful-api-yii2/
After that I have created :
api\modules\v1\controllers\SiteController.php
<?php
namespace api\modules\v1\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use common\models\LoginForm;
use yii\filters\VerbFilter;
use yii\rest\ActiveController;
/**
* Site controller
*/
class SiteController extends ActiveController
{
/**
* #inheritdoc
*/
public $modelClass = 'api\modules\v1\models\user';
public function actionIndex()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
And Created Model
RtWorkForce\api\modules\v1\models\User.php
<?php
namespace api\modules\v1\models;
use \yii\db\ActiveRecord;
/**
* User Model
*
*/
class User extends ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
}
Here Is my main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'modules' => [
'v1' => [
'basePath' => '#app/modules/v1',
'class' => 'api\modules\v1\Module'
]
],
'components' => [
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['v1/country','v1/user','v1/site'],
'tokens' => [
'{id}' => '<id:\\w+>'
]
]
],
]
],
'params' => $params,
];
But IT's not working i don't know where i am wrong ??
From Yii 2.0 REST Authentication docs :
Unlike Web applications, RESTful APIs are usually stateless, which
means sessions or cookies should not be used.
And from this other docs about the user class which implement yii\web\IdentityInterface :
if your application is a pure stateless RESTful application, you would
only need to implement findIdentityByAccessToken() and getId() while
leaving all other methods with an empty body.
RESTfull is about routing. If following a token based authentication, then, It should return a resources or a collections if the request sent to server is holding a valid token. Otherwise it should be rejected.
Login process in that case, is one request holding a username/password pair that will be exchanged with a valid token by server, that is the token you are going to include with all your next requests.
If session is disabled on server side by setting enableSession to false as described in Yii documentation (see links above) and as recommended by the stateless nature of REST, then \Yii::$app->user->isGuest should not provide info as your server won't have any session to get it from. (unless it verifies token validity instead of checking session)
When building a class extending yii\rest\ActiveController you can't render a html page like :
return $this->render('login', [
'model' => $model,
]);
or redirect to a different HTML page like :
return $this->goHome();
That will work with a yii\base\Controller when building a HTML based web app instead of yii\rest\ActiveController. with ActiveController you just return data which will be serialized to json or xml before output.
Please refer to Yii RESTful API framework documentations for more details. Then you may find useful information in this great tutorial on How to implement Yii2 REST Authentication :
http://blog.neattutorials.com/angularjs-and-yii2-part-2-authentication/

How to use yii2-user as sub-module inside another module

I want to implement one module in an existing application.In that module I am trying to use yii2-user module.The yii2 docs say we can do that.
namespace app\modules\forum;
class Module extends \yii\base\Module
{
public function init()
{
parent::init();
$this->modules = [
'admin' => [
// you should consider using a shorter namespace here!
'class' => 'app\modules\forum\modules\admin\Module',
],
];
}
}
I have module code as
namespace app\modules\cdas;
class cdas extends \yii\base\Module
{
public $controllerNamespace = 'app\modules\cdas\controllers';
public function init()
{
parent::init();
// custom initialization code goes here
$this->modules = [
'user' => [
'class' => 'dektrium\user\Module',
'modelMap' => [
'Profile' => 'app\modules\cdas\models\users\Profile',
'User'=>'aapp\modules\cdas\models\users\User',
],
'controllerMap' => [
'settings' => 'app\modules\cdas\controllers\user\SettingsController',
'admin' => 'app\modules\cdas\controllers\user\AdminController',
'role' => 'app\modules\cdas\controllers\user\RoleController',
'security' => 'app\modules\cdas\controllers\user\SecurityController',
],
];
}
}
But when I use the above methodology and try to access
http://localhost/<app_name>/web/cdas/user/security/login
I get the following error
PHP Notice – yii\base\ErrorException
Trying to get property of non-object
in ....vendor\dektrium\yii2-user\views\_alert.php
/**
* #var $module dektrium\user\Module
*/
<?php if ($module->enableFlashMessages): ?>
Please suggest proper way to implement the sub-module.

I have created a module using gii in yii2 , declared that in yii console.php in config , still can't access by index.php/moduleid

namespace app\modules\forum;
class Module extends \yii\base\Module
{
public $controllerNamespace = 'app\modules\forum\controllers';
public function init()
{
parent::init();
Yii::configure($this, require(__DIR__ . '/config.php'));
// custom initialization code goes here
}
}
this is my module class
and
'modules' => [
'gii' => 'yii\gii\Module',
'forum' => [
'class' => 'app\modules\forum\Module',
],
'test' => [
'class' => 'app\test\Module',
],
],
this is console.php in config , I am using basic of yii2